as the title sais, i'm trying to configure a local rest api server running node js and in the meantime i have a vue project with axios. i surfed the whole internet, tried every server/client configuration, server headers settings, cors package, axios header config, but i still have cors policy error inthe console. postman works by calling localhost:3000/everyapiPOSTorGet, but axios from the browser dont. could everyone indicate some working fix?
here is my actual node configuration:
const express = require("express");
const PORT = process.env.port || 3000;
const apiRouter = require('./routes');
const app = express();
app.use(express.json())
app.use('/', apiRouter)
// CORS middleware
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header(
"Access-Control-Allow-Headers",
"Authorization, X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Allow-Request-Method"
);
res.header("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, DELETE");
res.header("Allow", "GET, POST, OPTIONS, PUT, DELETE");
next();
})
app.listen(PORT, () => {
console.log("Server is listening on port: ", PORT);
});
thank you!
edit: i forgot to say that obviously vue project goes on localhost:8080 or 8081 (depends if i have more project running) and the server on localhost:3000
vue-cli
? – ljubadrvue-cli
you can avoid the CORS issues by setting up proxy. In your example, you could use thisdevServer: { port: 8080, proxy: { '/api': { target: 'http://localhost:3000', changeOrigin: true, } } },
. This means that if you calllocalhost:8080/api
call will be proxied to your backend onlocalhost:3000/api
– ljubadr