peppeg85
peppeg85

Reputation: 87

configure nodejs rest api server and vue project with axios cors policy error

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

Upvotes: 0

Views: 1567

Answers (1)

ljubadr
ljubadr

Reputation: 2254

Even though your question is how to configure and fix CORS errors, locally we can actually skip CORS altogether by using the webpack devServer proxy setting

With vue-cli you need to update vue.config.js file in your project root. If you don't have this file, create it

module.exports = {
  "devServer": {
    "port": 8080,
    "proxy": {
      "/api": {
        "target": "http://localhost:3000",
        "changeOrigin": true
      }
    }
  }
}

where 8080 is your frontend port (vue) and 3000 is your backend port (nodejs)

After this update make sure to restart your vue-cli npm run serve to see the proxy effect

What this setting does is that if you call http://localhost:8080/api/..., call will be proxied to your backend on http://localhost:3000/api/... and CORS issues should be gone

Upvotes: 1

Related Questions