-1

I'm creating an API with nodejs and express and a vue application but I'm getting the "No 'Access-Control-Allow-Origin' problem" when I request data to my API. I tried some solutions like use cors package and define response headers but I got the same error. If I do the request in postman, I get the response with the headers set. I don't know why I'm still in this problem.

Tried solutions:

app.use(cors({origin: '*', credentials: true}));
app.use((req, res, next) => {
    // Website you wish to allow to connect
    res.setHeader('Access-Control-Allow-Origin', '*');

    // Request methods you wish to allow
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

    // Request headers you wish to allow
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

    // Set to true if you need the website to include cookies in the requests sent
    // to the API (e.g. in case you use sessions)
    res.setHeader('Access-Control-Allow-Credentials', true);

    // Pass to next layer of middleware
    next();
});

My code:

app.js

'use strict';

const express = require('express');
const bodyParser = require('body-parser');
const usersRoute = require('./routers/users-route');
const cors = require('cors');


const app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));

app.use('/store', usersRoute);

// creating a route to my vue application
app.use(express.static('public'));

module.exports = app;

server.js

'use strict';

const http = require('http');
const debug = require('debug')('nodejsservers:server');

const app = require('../src/app');

const port = normalizePort(process.env.PORT || '3000');
app.set('port', port);

const server = http.createServer(app);


server.listen(port);
server.on('error', onError);
server.on('listening', onListening);

console.log('API rodando na porta: ' + port);

function normalizePort(val){
    const port = parseInt(val, 10);

    if(isNaN(port)) return val;
    if(port >= 0) return port;
    return false;
}

function onError(error){
    if(error.syscall !== 'listen') throw error;

    const bind = typeof port === 'string' ? 'Pipe ' + port :  'Port ' + port;

    switch(error.code){
        case 'EACCES':
            console.error(`${bind} requires elevated privileges`);
            process.exit(1);
            break;
        case 'EADDRINUSE':
            console.error(`${bind} is already in use`);
            process.exit(1);
            break;
        default: 
            throw error;
    }
}

function onListening(){
    const addr = server.address();
    const bind = typeof addr === 'string' ? 'pipe ' + addr : 'port ' + addr.port;
    debug('Listening on ' + bind);
}
  • 1
    `const server = http.createServer(app);` that's not how you use `express` – Bravo Jun 23 '22 at 04:09
  • You cannot use `*` origins with `Access-Control-Allow-Credentials` and should have received a warning informing you of such. Do you even need credential (aka cookie) support? It's more trouble than it's worth IMO – Phil Jun 23 '22 at 04:36

1 Answers1

2

You just configure cors, To a specific domain or multiple domains in an array:

   var cors = require('cors');

// use it before all route definitions

app.use(cors({origin: 'http://localhost:3000',credentials: true}));  

app.use(cors({origin: ['http://localhost:8001','http://localhost:8000'],credentials: true})); 
tirth1620
  • 154
  • 1
  • 8