Ad

How To Solve No 'Access-Control-Allow-Origin' In Express Js?

- 1 answer

I know that this question has been answered and some of them worked but for me it is not. I'm struggling to find a solution for this problem:

 Access to XMLHttpRequest at 'http://lolcahost:9000/api/users' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I already tried downloading a chrome extension but didn't help me and using app.use(cors()) also didn't help me.

This is my code in expressjs

    /* Importing all necessary packages. */
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');

/* Default port */
const port = process.env.PORT || 9000;
/* Creating express object */
const app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use('/api', require('./routes/route'));
app.use(cors());


app.get('/', (request, response) => {
    response.json({
        HOME: "HELLO JSON"
    })
});

app.listen(port, () => {
    console.log(`Listening at port ${port}`)
});

and this is my code in vuejs where I'm trying to render the data.

getUsers() {
            axios
                .get("http://localhost:9000/api/users/")
                .then(response => (this.results = response.data))
                .catch(error => console.log(error));
        }
Ad

Answer

You are using the cors middlware AFTER the /api routes. So, actually the cors middlware is not even being called. Put the cors above other middlwares.

const app = express();

app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use('/api', require('./routes/route'));

Middlwares are called by the order they are initialised. Now, the /api is initialised first and is not a middleware(doesn't call the next() function) so after the routes any middleware is basically unreachable code.

Ad
source: stackoverflow.com
Ad