2015-07-13 53 views
2

我正在使用parse.com來託管我的應用程序。我已經構建了一個反饋json的簡單api。網址很簡單,如下所示:http://websitename.parseapp.com/api/new/1/10。現在,我已經公開了我的api,但我想限制訪問,因此只有來自同一域名的頁面才能訪問它。 如何通過express.js實現此目的?express.js限制api只能訪問來自同一網站的頁面

這裏是什麼,我有一個示例代碼:

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(); 
+0

您可以使用'req.get('host')'來檢查請求是否來自該主機。但是任何人都可以欺騙這個標題。 – hassansin

回答

1

你想阻止Cross-origin resource sharing,它已經被阻止express.js。若要允許某些網站,您必須設置Access-Control-Allow-OriginAccess-Control-Allow-Headers(請參閱here)。

如果您向其他域創建HTTP請求,那麼您必須發送包含請求域的HTTP頭(Origin)。基於此,網絡服務器決定是否響應該請求。

如果您想阻止所有域中的CORS,但是該網站的主機位於:您無需執行任何操作。

如果您想允許某些網站使用該網址,請將Access-Control-Allow-Origin-標題改爲所需的域名。