js限制API只能访问来自同一网站的页面

express.js limit api access to only pages from the same website

本文关键字:网站 API 限制 访问 js      更新时间:2023-09-26

我使用parse.com来托管我的应用程序。我建立了一个简单的api,反馈json。url很简单,像这样:http://websitename.parseapp.com/api/new/1/10。现在,我的api是公开可见的,但我想限制访问,所以只有来自相同域名的页面才能访问它。我如何用express.js实现这一点?

下面是我的示例代码:

var express = require('express');
var app = express();
// Global app configuration section
app.set('views', 'cloud/views');  // Specify the folder to find templates
app.set('view engine', 'ejs');    // Set the template engine
app.use(express.bodyParser());    // Middleware for reading request body
// This is an example of hooking up a request handler with a specific request
// path and HTTP verb using the Express routing API.
app.get('/api/:page/:from/:to', function(req, res) {
  res.render('hello', { message: 'Congrats, you just set up your app!' });
});
// This line is required to make Express respond to http requests.
app.listen();

您希望防止跨域资源共享,而express.js已经阻止了跨域资源共享。为了允许它从某些网站,你必须设置Access-Control-Allow-OriginAccess-Control-Allow-Headers(见这里)。

如果你创建一个HTTP请求到一个不同的域,你在那里必须发送一个Origin HTTP头包括请求域。在此基础上,web服务器决定是否响应请求。

如果你想阻止CORS从所有的域,除了一个网站的托管: 你不需要做任何事情

如果你想允许它从某些网站,更改Access-Control-Allow-Origin -头为您想要的域名。