I am facing a problem when hosting an socket io application on heroku. The browser keep saying Access to XMLHttpRequest at from origin has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
However, I already setup the server side with cors. Below I attach my server index.js
.
Server index.js
const express = require("express");
const app = express();
const http = require("https");
const { Server } = require("socket.io");
const cors = require("cors");
const server = http.createServer(app);
const user = [];
const io = new Server(server, {
cors: {
origin: process.env.PORT || 5000,
methods: ["GET", "POST"],
},
});
const corsOptions ={
origin: process.env.PORT || 5000,
credentials:true, //access-control-allow-credentials:true
optionSuccessStatus:200
}
app.use(cors(corsOptions));
io.on("connection", (socket) => {
user.push(socket.id);
// console.log(`User Connected ${socket.id}`);
socket.on("join_room", (data) =>{
socket.join(data);
})
socket.on("send_message", (data) => {
let new_data = {user_id: data.id, msg: data.text};
socket.to(data.room).emit("receive_message", new_data);
})
});
server.listen(process.env.PORT || 5000, () => {
console.log("SERVER OK");
});
Please give me any hint since i tried so many solution that doesnt work.
At the origin
propery of corsOptions
you have specified only the port, but you need the full origin (eg http://localhost:5000
). So this might work:
const corsOptions ={
origin: "http://localhost:" + (process.env.PORT || 5000),
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// whatever origin (protocol://full.domain.name:port) calling the server
credentials:true, //access-control-allow-credentials:true
optionSuccessStatus:200
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.