NodeJS Express App不能调用app.use

我有一个NodeJS应用程序,我用作游戏服务器。

我正在尝试设置CORS,但是app.use似乎没有被调用。

任何人知道为什么

var util = require("util"); // Utility resources (logging, object inspection, etc) var fs = require('fs'); var express = require("express"); var app = express(); var port = 3000; app.use(function (req, res, next) { // these never get printed out: util.log( "app.use adding Access-Control-Allow-Origin" ); console.log( "app.use adding Access-Control-Allow-Origin" ); // Website you wish to allow to connect res.setHeader('Access-Control-Allow-Origin', 'https://example.com'); // Request methods you wish to allow res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE'); // Request headers you wish to allow res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type'); // Set to true if you need the website to include cookies in the requests sent // to the API (eg in case you use sessions) res.setHeader('Access-Control-Allow-Credentials', true); // Pass to next layer of middleware next(); }); var server = app.listen(port, function(){ console.log('CORS-enabled web server listening on port ' + port); }); var io = require('socket.io').listen(server); 

检查npm cors包裹。 https://www.npmjs.com/package/cors

所有请求都将启用CORS的示例用法:

 var express = require('express') , cors = require('cors') , app = express(); app.use(cors()); app.get('/my_API_URL/:id', function(req, res, next){ res.json({msg: 'This is CORS-enabled for all origins!'}); }); app.listen(80, function(){ console.log('CORS-enabled web server listening on port 80'); }); 

在他们的页面上,他们还获得了CORS仅在单一path上启用的其他示例。

另外,只是想知道你如何testing你的应用程序? 示例代码中没有定义任何路由。


正如评论部分所指出的,@Nitzan Wilnai并没有在做REST API,对于混淆道歉。 假设它是一个简单的服务器,在某个端口上侦听,所以对于这种情况你根本不需要expression 。 有一些研究和解决scheme出来了;

 io.configure('development', function(){ io.set('origins', '*:*'); } 

要么

 io.set( 'origins', '*domain.com*:*' ); 

参考: Socket.io不设置CORS标头(s)

万一你正在尝试build立一个聊天程序。 这是一个示例项目; https://github.com/socketio/socket.io