Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
116 views
in Technique[技术] by (71.8m points)

node.js - Node js_CORS block access

I'm trying to communicate with the front react at localhost:3000 and the backend side nodeJS is localhost:5000 but the problem I keep getting this message and I can't find a solution how to solve it

Access to XMLHttpRequest at 'http://localhost:5000/socket.io/?EIO=3&transport=polling&t=NSheHsx' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

GET-polling-xhr.js:268 GET http://localhost:5000/socket.io/?EIO=3&transport=polling&t=NShel1V net::ERR_FAILED

I tried every solution on the internet but without any chance

var corsOptions = {
  origin: "https://localhost:3000/",
  optionsSuccessStatus: 200, // some legacy browsers (IE11, various SmartTVs) choke on 204
};
app.use(cors(corsOptions));

this is the server.js

require("dotenv").config();
const express = require("express");
const morgan = require("morgan");
const cors = require("cors");
const loadRoutes = require("./routes/index");
const app = express();
var server = require("http").createServer(app);
var io = require("socket.io")(server);
const path = require("path");
let stream = require("./controllers/stream");
var corsOptions = {
  origin: "https://localhost:3000/",
  optionsSuccessStatus: 200, // some legacy browsers (IE11, various SmartTVs) choke on 204
};
app.use(cors(corsOptions));
app.use(express.json());
app.use(fileUpload());

// database config
require("./config/db");

//require config
require("dotenv").config({
  path: "./config/config.env",
});

//config for only developement

if (process.env.NODE_ENV === "developement") {
  app.use(
    cors({
      origin: process.env.CLIENT_URL,
    })
  );
}
app.use(morgan("dev"));
//load all routes
loadRoutes(app);


io.of("/stream").on("connection", stream);
//---------------------------------------------
app.use((req, res, next) => {
  res.status(404).json({
    success: false,
    message: "Page Not found",
  });
});

//start our web server and socket.io server listening
server.listen(process.env.PORT, function () {
  console.log(`listening on ${process.env.PORT}`);
})

changes that I made based on answer below but same error

require("dotenv").config();
const express = require("express");
const morgan = require("morgan");
const cors = require("cors");
const loadRoutes = require("./routes/index");
const app = express();
var server = require("http").createServer(app);
var io = require("socket.io")(server);
const path = require("path");
let stream = require("./controllers/stream");
var corsOptions = {
  origin: "http://localhost:3000/",
  optionsSuccessStatus: 200, // some legacy browsers (IE11, various SmartTVs) choke on 204
};
// add this headers to your request and yow problems will be gone.
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");
    next();
});

app.use(cors(corsOptions));
app.use(express.json());
app.use(fileUpload());

// database config
require("./config/db");

//require config
require("dotenv").config({
  path: "./config/config.env",
});

//config for only developement

if (process.env.NODE_ENV === "developement") {
  app.use(
    cors({
      origin: process.env.CLIENT_URL,
    })
  );
}
app.use(morgan("dev"));
//load all routes
//cors anwser2
app.option("*",cors())
    loadRoutes(app);
    

io.of("/stream").on("connection", stream);
//---------------------------------------------
app.use((req, res, next) => {
  res.status(404).json({
    success: false,
    message: "Page Not found",
  });
});

//start our web server and socket.io server listening
server.listen(process.env.PORT, function () {
  console.log(`listening on ${process.env.PORT}`);
})

Any idea on solving this error ?

question from:https://stackoverflow.com/questions/65851842/node-js-cors-block-access

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

have you already tried enabling PREFLIGH like described on 'cors' lib? There is a section on the docs explaining about 'complex' requests that need to make a preflight request before making the actual request.

Here is a simple way to enable to test:

app.options('*', cors()) // include before declaring the route

I got this information from this section on the readme here: https://www.npmjs.com/package/cors#enabling-cors-pre-flight

Tho it's not recomended using wildcard '*' in production, so be careful :) hope I helped


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...