Reputation: 109
I made a client-server application. The backend uses Node, Express and MongoDB Atlas.
I already installed CORS and used it as a middleware like:
const cors = require('cors')
app.use(cors())
Then I deployed it to heroku which returned an endpoint; like : https://express-server.herokuapp.com
I used that endpoint in my client which is based on React.
I use axios to make a request to the server such as:
const response = await axios.post('https://express-server.herokuapp.com/users/login' ,{some data here})
This is where the error occurs. Every time I make a request the following response pops up in the console.
What is the solution for this????
Upvotes: 1
Views: 3610
Reputation: 108651
You need to support CORS preflight requests to do POST operations with json data. See this: Why is there no preflight in CORS for POST requests with standard content-type That means handling http OPTIONS.
Something like this in your express app, before other routes.
app.options('*', cors())
Upvotes: 0
Reputation: 192
Added to main.ts
app.enableCors({
origin: true,
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS',
credentials: true,
});
Upvotes: 0
Reputation: 26
You have to define in your server from which origin requests should be accepted
Assuming your localhost runs on port 3000. Try this code
app.use(
cors({
origin: "http://localhost:3000",
credentials: true,
})
);
NOTE: credentials true is set to pass HTTP only cookies
Upvotes: 1