Reputation: 1328
Hey guys i was making a MERN stack project so the issue i am facing is that in action creater from react server i have to make a get request to node js server or in short
From http://localhost:3000/ i have to make request to the data i have in http://localhost:5000/api/currentuser
The data stored in nodejs server is {"_id":"5d73fd9003b5302f6b013a46","googleid":"109463598810933991924","__v":0}
which is being fetched from mongodb
So what i did is inside my action creater file
i did like
import axios from "axios";
export const fetchuser = () => {
return async(dispatch)=>{
const res=await axios.get("http://localhost:5000/api/currentuser")
dispatch({
type:'fetchuser',
payload:res.data
})
}
};
but then in my console i faced the error and it says
Access to XMLHttpRequest at 'http://localhost:5000/api/currentuser' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Upvotes: 0
Views: 53
Reputation: 153
This is cross origin issue.You have not provided access to http://localhost:3000/ in nodejs.
There are two simple ways,
1. Simple way without any npm package:
app.use(function (req, res, next) {
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000');
// methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
/ headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
next();
});
2. Use cors npm package:
Official document url https://expressjs.com/en/resources/middleware/cors.html
-To allow all domain/url
import cors from 'cors';
app.use(cors());
You will notice new header is being returned as Access-Control-Allow-Origin: *
-To allow specific domain/urls,
import cors from 'cors';
app.use(cors({
origin: 'http://localhost:3000/'
}));
Header will be,
Access-Control-Allow-Origin: http://localhost:3000
Upvotes: 1
Reputation: 5650
Without having the Express code it's hard to be confident but you likely need to configure the Express server to have CORS setup.
You can see the docs here for Express + CORS: https://expressjs.com/en/resources/middleware/cors.html
var express = require("express");
var cors = require("cors");
var app = express();
app.use(
cors({
origin: "http://localhost:3000"
})
);
For more details on CORS in general, read this.
Upvotes: 1