[英]Socket.io + Nodejs + Angular2+ - CORS header 'Access-Control-Allow-Origin' missing
I am doing a MEAN stack application. 我正在做一个MEAN堆栈应用程序。 To communicate between the client and the server I use some HTTP requests and websockets. 为了在客户端和服务器之间进行通信,我使用了一些HTTP请求和Websocket。 On the localhost it works fine. 在本地主机上,它可以正常工作。
But then, when I try to deploy the application from localhost to a specific server, the websockets are not working anymore. 但是,当我尝试将应用程序从localhost部署到特定服务器时,WebSocket不再起作用。 However, http requests work fine. 但是,http请求可以正常工作。
I got this warning: 我收到此警告:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://138.250.31.29/socket.io/?userId=5b7c030dca40486dabaafaaf&EIO=3&transport=polling&t=MM5TZt_ . 跨域请求被阻止:“相同源策略”不允许读取位于http://138.250.31.29/socket.io/?userId=5b7c030dca40486dabaafaaf&EIO=3&transport=polling&t=MM5TZt_的远程资源。 (Reason: CORS header 'Access-Control-Allow-Origin' missing). (原因:CORS标头“ Access-Control-Allow-Origin”缺失)。
In order to establish the connection I have two files on Node.JS: 为了建立连接,我在Node.JS上有两个文件:
APP.JS APP.JS
const createError = require("http-errors");
const express = require("express");
const path = require("path");
const logger = require("morgan");
const favicon = require("serve-favicon");
const cors = require("cors");
require("./models/db");
require("./config/passport");
const passport = require("passport");
const apiRouter = require("./routes/index");
const corsOptions = {
origin: "*",
optionsSuccessStatus: 200
};
const app = express();
app.use(logger("dev"));
app.use(express.json({ limit: "1gb" }));
app.use(express.urlencoded({ extended: false }));
app.use(passport.initialize());
app.use(cors(corsOptions));
app.use("/api", apiRouter);
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept"
);
res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
next();
});
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get("env") === "development" ? err : {};
// render the error page
res.status(err.status || 500);
res.render("error");
});
// error handlers
// Catch unauthorised errors
app.use(function(err, req, res, next) {
if (err.name === "UnauthorizedError") {
res.status(401);
res.json({ message: err.name + ": " + err.message });
}
});
module.exports = app;
WWW 万维网
!/usr/bin/env node
/**
* Module dependencies.
*/
const app = require("../app");
const debug = require("debug")("sorfml:server");
const http = require("http");
const socketIO = require("socket.io");
/**
* Get port from environment and store in Express.
*/
const port = normalizePort(process.env.PORT || "3000");
app.set("port", port);
/**
* Create HTTP server.
*/
const server = http.createServer(app);
/**
* Bind the socket.IO with the http server
*/
const io = socketIO(server);
io.origins("*:*");
clientsList = {};
/**
* Socket connection
*/
io.on("connection", socket => {
console.log("Client connected " + socket.id);
socket.user_id = socket.handshake.query.userId;
clientsList[socket.handshake.query.userId] = socket;
socket.on("disconnect", () => {
delete clientsList[socket.user_id];
console.log("Client disconnected: " + socket.id);
});
});
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port);
server.on("error", onError);
server.on("listening", onListening);
/**
* Normalize a port into a number, string, or false.
*/
function normalizePort(val) {
const port = parseInt(val, 10);
if (isNaN(port)) {
// named pipe
return val;
}
if (port >= 0) {
// port number
return port;
}
return false;
}
/**
* Event listener for HTTP server "error" event.
*/
function onError(error) {
if (error.syscall !== "listen") {
throw error;
}
const bind = typeof port === "string" ? "Pipe " + port : "Port " + port;
// handle specific listen errors with friendly messages
switch (error.code) {
case "EACCES":
console.error(bind + " requires elevated privileges");
process.exit(1);
break;
case "EADDRINUSE":
console.error(bind + " is already in use");
process.exit(1);
break;
default:
throw error;
}
}
/**
* Event listener for HTTP server "listening" event.
*/
function onListening() {
const addr = server.address();
const bind = typeof addr === "string" ? "pipe " + addr : "port " + addr.port;
console.log("Listening on " + bind);
}
On the client side (Angular): 在客户端(角度):
import * as io from "socket.io-client";
private socket;
this.socket = io("ws://138.250.31.29/sorfml_api", { query: "userId=" + userId });
this.socket.on("sendNotification", data => {
// Do a function
});
this.socket.on("deleteNotificationFromAuthor", data => {
// Do a function
});
I found many questions about it on Stackoverflow and Github but nothing fix my problem. 我在Stackoverflow和Github上发现了很多关于它的问题,但是没有什么能解决我的问题。
I tried to set the origins like this (in the www file): 我试图这样设置起源(在www文件中):
io.set('origins', '*:*');
or 要么
io.set('origins', 'http://138.250.31.29:80');
Then in the app.js file, I tried also to add more authorization in the corsOptions and in the app.use(). 然后在app.js文件中,我还尝试在corsOptions和app.use()中添加更多授权。 But nothing works. 但是什么都行不通。
I guess your io.set('origins', ':');
我猜你是io.set('origins', ':');
statement is wrong, 陈述是错误的,
it should be either, 应该是
io.set('origins', '*:*');
or 要么
io.origins('*:*')
Hope this helps! 希望这可以帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.