Categories
Mastering Development

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

Leave a Reply

Your email address will not be published. Required fields are marked *