I am setting up a rest api for a personal site. My personal site is built with Vue.js and the api server is built with express. I have tried a couple different CORS configurations on the server but I seem to still get the pre-flight error so I assume I am lacking understanding somewhere.
The original goal was for me to learn about docker by containerizing the api/auth server and hosting it separately from the frontend vue.js app. Is this a part of the problem or bad practice?
Below are the two CORS configs I tried which I found on other posts but have had no success with.
Config #1:
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "http://0.0.0.0:5000"); // I tried setting a specific IP as well as the * wildcard
res.header("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,OPTIONS");
res.header("Access-Control-Allow-Headers", "Content-type,Accept,X-Custom-Header");
// I think this if statement should respond the preflight request.
if (req.method === "OPTIONS") {
return res.status(200).end();
}
return next()
})
Config #2:
const whitelist = [
'http://0.0.0.0:5000',
];
const corsOptions = {
origin: function(origin, callback){
var originIsWhitelisted = whitelist.indexOf(origin) !== -1;
callback(null, originIsWhitelisted);
},
credentials: true
};
app.use(cors(corsOptions));
I am also wondering if it has something to do with how I'm making the request so I've added the method that is being used from the Vue.js app:
attemptLogin: function(event) {
event.preventDefault()
axios.post('http://0.0.0.0:5000/auth/login', {
username: this.username,
password: this.password
})
.then(res => {
if (res.data.success) {
this.updateLoginStatus()
this.updateJwt(res.data.token)
}
})
.catch(error => {
console.log(error)
});
}
Other potentially useful information:
I tried running both the frontend and the backend on the same computer with no luck. Now I am running the backend on my laptop and the frontend on my desktop.
Here are the GitHub Repos for both repositories if you need more context: