Reputation: 191
I have my micro-service developed using spring-boot and spring security and frontend is designed on react-hooks. Now, while I am send some data to my micro-service using axios.post method, it send CORS preflight method i.e. options method because axios by default send content-type as application/json and application.json leads to send options request to server before any other request.
I have tried sending my request with different headers and content types as 'application/x-www-form-urlencoded' also I have used @cross-origin(*) at my server end.
const config = {
headers: {
'Content-Type': 'application/json'
}
}
const response = await axios.post(ps.user_ms_url+ps.user_login,
{
username:values.email,
password:values.password
// headers:{'tokenvalue':'token'}
},
config);
I expect my browser to send only post request to the server, for that I am ready to change my headers as well. Any help will be appreciated. Thanks in advance!
Upvotes: 4
Views: 19477
Reputation: 191
I found the solution for my query. As I mentioned above, our browser sends preflight request (means options request) before any other request if our request is not simple (here simple means: if request contains content-type : application/json or custom headers etc) and if we are sending this request to some other domain/ URL.
And our axios.post method carries content-type as application/json by default, that's why, my browser was sending multiple requests (means preflight request before any other request).
Now, I have changed my request content-type to application/x-www-form-urlencoded by sending data as params, as shown below:
var params = new URLSearchParams();
params.append('username', values.email);
params.append('password', values.password);
const response = await axios.post(ps.user_ms_url+ps.user_login,
params);
And handling this request at backend using @ModelAttribute annotation (Spring-boot). So, keeping request simple can stop preflight requests.
Upvotes: 3
Reputation: 1681
You can avoid CORS preflight request by proxying the request. Add this in your webpack development config
devServer: {
port: process.env.PORT || 3000,
proxy: {
'/api': {
target: 'http:localhost:8080',
pathRewrite: { '^/api': '' },
changeOrigin: true,
},
},
}
This means your request to /api/users
will forwarded to http://localhost:8080/users
.
If you are using create-react-app. just add "proxy": "http://localhost:8080"
to your package.json. Check more info here
Upvotes: 1
Reputation: 11257
This looks to be server side CORS issue. You have to allow domains to access resources by providing correct response headers.
You can look at adding CORS headers in spring boot. Refer to this link
Hope that helps!!!
Upvotes: 0