I’m trying to make a side project to implement node.js with Vue.js. I’m stuck with this CORS error when I try to register a user on my register Vue Component. I tried many things I saw in stack overflow issues and node.js, CORS documentation,… but still I’m stuck with this error : The ‘Access-Control-Allow-Origin’ header has a value ‘http://localhost:3000/’ that is not equal to the supplied origin.
Here my index.js :
import mongoose from 'mongoose';
import user from './api/routes/user.js';
import express from 'express';
import dotenv from 'dotenv';
import cors from 'cors';
dotenv.config();
const app = express()
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "http://localhost:8080/");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.options('http://localhost:8080/', cors())
const corsOptions = {
origin: 'http://localhost:8080/',
optionsSuccessStatus: 200,
methods: "GET, PUT, POST, DELETE"
}
mongoose.connect('mongodb://localhost/myDatabaseName', {
useNewUrlParser: true,
useUnifiedTopology: true
} )
.then(() => console.log('connected to mongoDb'))
.catch((err) => console.error('could not connect to mongoDb..', err));
app.use(express.json())
app.use('/api/user', user)
app.use(cors(corsOptions));
const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`Listening on port ${port}`))
First, I try only with CORS Lines (corsOption) and then without CORS lines, but it doesn’t work.
Here my Axios config file :
import axios, { AxiosRequestConfig } from 'axios';
const Axios = axios.create({
// baseURL: process.env.VUE_APP_API_URL || '/api',
baseURL: 'http://localhost:3000/api',
withCredentials: true,
headers: {
'Content-Type': 'application/json',
},
});
Axios.interceptors.request.use((config: AxiosRequestConfig) => {
if (!config.method) {
return config;
}
const method = config.method.toUpperCase();
if (method !== 'OPTIONS') {
config.headers = {
...config.headers,
AUTHORIZATION: localStorage.getItem('JWT_ACCESS'),
};
}
return config;
});
Here is my API call in my Vue.JS Component :
private async submit() {
try {
const response = await registerApi.register(this.userBis);
localStorage.setItem('JWT_ACCESS', response);
localStorage.setItem('IS_SIGNED', 'true');
} catch (err) {
console.error(err);
}
}
Thanks in advance!