Help with CORS API NODE JS

2

How could someone help me with the Cors in nodejs, I am already using the npm of cors but it does not work or I think I am not configuring them in an appropriate way, when consuming other apis that lend themselves to the testing of them it does not happen this problem and the sentences are executed correctly ps I am consuming it in ionic3

const express = require('express');
const app = express();
const cors = require('cors');
const morgan = require('morgan');
const bodyParser = require('body-parser');

//settings
app.set('port', process.env.PORT || 3000);

//middleware
app.use(morgan('dev'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.use(cors())

app.get('/animales', function(req, res, next) {
    res.json({ msg: 'This is CORS-enabled for all origins!' })
})

app.listen(80, function() {
    console.log('CORS-enabled web server listening on port 80')
})

//routes
require('../routes/userRoutes')(app);
require('../routes/ganaRoutes')(app);

app.listen(app.get('port'), () => {
    console.log('Server en el puerto 3000');
});

And here in the Chrome console

    
asked by David Herrera 30.09.2018 в 01:18
source

1 answer

0

I have never used the cors package, but I use the CORS (HTTP Access Control) configuring Express in the following way:

const express = require('express');
const app = express();
const bodyParser = require('body-parser');



app.use((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();
}) 

Access-Control-Allow-Origin : To control who can consume my API

Access-Control-Allow-Headers : To configure the headers that the API accepts

Access-Control-Allow-Methods : To declare the methods accepted by the API

I've always done it like that and I've never had any problems, I hope it works for you.

    
answered by 28.10.2018 в 04:05