Prashant Gupta
Prashant Gupta

Reputation: 790

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

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).

Upvotes: 4

Views: 10626

Answers (2)

Ankit Kumar Rajpoot
Ankit Kumar Rajpoot

Reputation: 5590

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())

Upvotes: 1

GreatDharmatma
GreatDharmatma

Reputation: 667

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);

Upvotes: 6

Related Questions