我有一个跨域问题,通过Socket.io从localhost连接到Nodejitsu的远程服务器。我收到错误" ...标题包含多个值' http://evil.com/,*',但只允许一个"。更多详情如下:
我在Nodejistu上运行的Express / Mongoose / Socket.io应用程序用作REST API,它不提供HTML文件。
本地我有一个Angularjs + Requirejs应用程序(在http://localhost:8000运行)尝试连接到远程API而我无法访问。虽然我可以使用POSTMAN测试API方法并且能够从Angular RequireJS应用程序读取socket.io脚本前端,但是连接未被授予访问权限并导致服务器崩溃循环。
在Nodejitsu上的NodeJS / Express 应用中,我设置了以下内容:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var morgan = require('morgan');
var port = process.env.PORT || 80; // set our port the same as Nodejitsu
// ATTACHING SOCKET.IO
var server = require('http').createServer(app);
var io = require('socket.io')(server);
app.set('socketio', io); // socket instance of the app
app.set('server', server);
// CONFIGURE BODY PARSER
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
//CORS SETTING
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "http://localhost:8000");
res.header("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,OPTIONS");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.header("Access-Control-Allow-Credentials", "false");
next();
});
// START SERVER
app.get('server').listen(port);
---------
// package.json
"dependencies": {
"express": "4.11.1",
"morgan": "1.5.1",
"mongoose": "3.8.21",
"body-parser": "1.10.2",
"grunt-release": "0.10.0",
"socket.io": "1.3.2"
},
在localhost:8000的 Angular 应用中,我检查了Header是否重复,如附加的png所示。
// main.js
"use strict";
require.config({
paths: {
...
'socketio': 'http://<MYAPP>.jit.su/socket.io/socket.io';,
...
// SocketFactory.js
var socket = io.connect('http://<MYAPP>.jit.su:80/api/boards');
但是我收到此错误消息,即使我将Origin设置为localhost:// 8000:
XMLHttpRequest cannot load http://<MYAPP>.jit.su/socket.io/?EIO=3&transport=polling&t=1423052553506-7.
The 'Access-Control-Allow-Origin' header contains multiple values
'http://evil.com/, *', but only one is allowed.
Origin 'http://localhost:8000'; is therefore not allowed access.
答案 0 :(得分:0)
我得到了同样的错误,但最终它甚至都不是CORS问题。在using socket.io with express时,请按照socket.io的文档中的说明在服务器而不是应用上收听。
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(80);
(...)