How to solve CORS request did not succeed in express.js when react client try fetch data?

百般思念 提交于 2020-01-15 03:29:06

问题


I done so many changes in app.js file to solve this issue CORS request did not succeed but i always facing the same issue.How to solve this issue. I added my app.js code please check anyone. thanks

app.js Code

var express = require('express');

var bodyParser = require("body-parser");
var app = express();
var cors = require('cors');

const userlogin   = require('./routes/User_route');
const deviceRoutes = require("./routes/Device_route");

app.use('*', cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.set('port', process.env.PORT || 4007);
app.set('host', "*.*.*.*"); 

app.use("/users",userlogin);
app.use("/users", deviceRoutes);
module.exports = app;

Error

TypeError: "NetworkError when attempting to fetch resource." bundle.js:132447:16

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:4007/users/login. (Reason: CORS request did not succeed).


回答1:


You can try adding a middleware to handle CORS.

//CORS middleware
var corsMiddleware = function(req, res, next) {
    res.header('Access-Control-Allow-Origin', 'localhost'); //replace localhost with actual host
    res.header('Access-Control-Allow-Methods', 'OPTIONS, GET, PUT, PATCH, POST, DELETE');
    res.header('Access-Control-Allow-Headers', 'Content-Type, X-Requested-With, Authorization');

    next();
}

app.use(corsMiddleware);



回答2:


You can use cors npm in express.

npm install cors

Update app.js

var express = require('express')
var cors = require('cors')
var app = express()

app.use(cors())


来源:https://stackoverflow.com/questions/52361226/how-to-solve-cors-request-did-not-succeed-in-express-js-when-react-client-try-fe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!