I have deployed my express JS API to Heroku here:
https://mylink.herokuapp.com/somefile/do-somestuff
I have my React JS app on http://localhost:3000
The Heroku API works perfectly well when I consume it using PostMan. However, when I consume it using React JS App, I get the following error:
localhost/:1 Access to XMLHttpRequest at 'https://mylink.herokuapp.com/somefile/do-somestuff' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. mylink.herokuapp.com/somefile/do-somestuff:1 Failed to load resource: net::ERR_FAILED
Here is my Express JS API:
const express = require('express');
const app = express();
const myRouter = require('./someFile');
const cors = require('cors');
app.listen(process.env.PORT, () =>{
console.log(`App is listening on port 5000`);
});
app.use(cors(/**{
origin: `http://localhost:3000`, //react's address
credentials: true
}*/));
app.use(express.json());
app.use('/somefile', someFile);
app.get('/', (request, response) =>{
response.send('Homepage');
});
module.exports = app;
In someFile.js:
const express = require('express');
const app = express();
const router = express.Router();
router.post('/do-somestuff', async (request, response) =>{
let token = request.body.passedtoken;
let latestOTP = await otpCodeModel.find({someField:token}).sort({_id: -1}).limit(1);
return response.json({message: latestOTP});
});
module.exports = router;
Here is my React Code:
class App extends React.Component{
constructor(props){
super(props);
}
sendPassedToken = (token) => {
axios.post(`https://mylink.herokuapp.com/somefile/do-somestuff`, token)
.then((response) => {
console.log(response.data.message);
}).catch((error) => {
console.log(error);
});
console.log(token);
}
}
export default App;
What is the problem, why it's not working and always throwing the following error when consuming the heroku api from React JS:
localhost/:1 Access to XMLHttpRequest at 'https://mylink.herokuapp.com/somefile/do-somestuff' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. mylink.herokuapp.com/somefile/do-somestuff:1 Failed to load resource: net::ERR_FAILED
CodePudding user response:
You might need to modify the client's axios request headers to set withCredentials: true
and/or credentials: 'include'
.
React Code:
class App extends React.Component{
constructor(props){
super(props);
}
sendPassedToken = (token) => {
axios
.post(
`https://mylink.herokuapp.com/somefile/do-somestuff`,
token,
{ withCredentials: true, credentials: 'include' }
)
.then((response) => {
console.log(response.data.message);
}).catch((error) => {
console.log(error);
});
console.log(token);
}
}
export default App;
I know you probably already know this, but just be sure you're uncommenting this out when you're running your backend. Seems like this is set up fine:
app.use(cors({
origin: `http://localhost:3000`, //react's address
credentials: true
}));
edit: I received a notification from you, but I guess you deleted the comment. Just keep in mind, if you haven't set headers from your axios request object somewhere else, you might have to in order to pass the cors pre-flight request. I believe you don't have to add credentials: 'include'
to an axios request(that may be for fetch), but you need to add withCredentials: true
for axios, unless you've set it on the axios object itself elsewhere. This type of cors set-up requires you to specify an origin and not "*" since you're setting credentials:true
, which you're doing on the backend.
So if you examine the request from the network tab in your browser dev tools, and you get certain things like--
A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' header when the credentials flag is true. Origin 'http://localhost:3010' is therefore not allowed access.
Then either that route, app, or cors module is incorrectly set up. Maybe you forgot to uncomment out the headers object you were sending into the cors module? If you set up a source code pipeline to Heroku, check the files in that branch, since it would be the code that's executing on that Heroku instance, and see if everything is set up correctly.
CodePudding user response:
You have to creat a schema so that you can send data to backend front end and try reinstalling cors . CORS enables you to access a resource from a different origin. It is used to override your browser's default behavior due to SOP. So now when your client requests a resource, the response will additionally contain a stamp that tells your browser to allow resource sharing across different origins.