Reputation: 33
I created the project using Sails + Vue and I will share the project on github with others.
I have a problem with cors.
In backend() sails the code of the security is:
module.exports.security = {
cors: {
allRoutes: true,
allowOrigins: '*',
allowCredentials: false,
},
csrf: false
};
In frontend(vue) I extends library axios, and create http
import axios from 'axios';
export const HTTP = axios.create({
baseURL: `http://localhost:1337`,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET,HEAD,OPTIONS,POST,PUT',
'Authorization': `Bearer ${localStorage.getItem('token')}`,
'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept, Authorization',
}
})
And a use the http in request
import {HTTP} from './http-common';
export default {
post (user) {
return HTTP.post('/api/v1/entrance/signup', user)
.then((response) => Promise.resolve(response))
.catch((error) => Promise.reject(error))
}
}
So, I using HTTP in post user I have problem with CORS. But I using axios in postUser, I don't have problem with CORS. The code:
import axios from 'axios';
export default {
post (user) {
return axios.post('http://localhost:1337/api/v1/entrance/signup', user)
.then((response) => Promise.resolve(response))
.catch((error) => Promise.reject(error))
}
}
I would like the suggestion to resolve the problem. Thanks people
Upvotes: 1
Views: 828
Reputation: 376
It's a common issue. You have your client running on port 8080 and your sails server on port 1337, these are considered different domains.
I usually advise people to use proxy on the clients side to proxy all the requests to server so there are no issues. This is especially helpful due to the way Sails.js sessions work with cookies. It is an easy setup if you are using webpack DevServer. Here is a link to DevServers documentation - proxy.
If you still want to fix CORS in this domain configuration you have to do so on the server side.
In your Sails.js applications root go to edit config/security.js
. There you will see a CORS settings commented out. It will look something like this:
// cors: {
// allRoutes: false,
// allowOrigins: '*',
// allowCredentials: false,
// },
Change it to allow your client local host domain like so:
cors: {
allRoutes: true,
allowOrigins: ['http://localhost:8080']
},
You can revert your client side changes.
Mind that you might need to add withCredentials
option to your axios call, without it the browser will not send any cookies.
axios.get('some api url', {withCredentials: true});
Upvotes: 1