1

Hy, I try to get some data from a nodeJs API. I use react for frontend. I make my node API, I test with Postman and it work fine. When I use axios for get my data from the server I get a cors Error.

This is my axios call from react:

async function getMagazin(){
    return (await axios.get(URL)).data; 
}

And this is my node Js API:

import express from 'express';
import bodyParser from 'body-parser';
import db from './dbConfig.js';
import Magazin from './entities/Magazin.js';
import cors from 'cors';

let app = express();
let router = express.Router();

app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use('/api', router);
app.use(cors());

app.use(function(req, res, next) {
    res.setHeader("Access-Control-Allow-Origin", "*"); 
    res.setHeader('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE'); 
    res.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    if ('OPTIONS' == req.method) {
       res.sendStatus(200);
     }
     else {
       next();
     }});

async function getMagazin(){
    return await Magazin.findAll();
}

router.route('/magazin').get(async (req, res) => {
    res.json(await getMagazin());
})

let port = process.env.PORT || 8000;
app.listen(port);
console.log("API is running at " + port);

I try to add cors in my node API and hope the error is gone but not.

This is the error:

enter image description here

I try to make I debug, the api call go on the server and execute sql query, but when he return he give me that error. What I must add in my server side code for the API to work?

2 Answers 2

1

Switch the order so that cors is before api

app.use(cors());
app.use('/api', router);
Sign up to request clarification or add additional context in comments.

1 Comment

app.use(cors()) should really be on top but without a deeper look that might break something.
0

When you use cors you have to indicate what domain or address can contact your api by adding it in the cors middleware like this:

   app.use(cors({
        origin: "http://localhost:3000"
    }));

2 Comments

it work, thanks, but first in the console he give me the error, and after this he give me the data.
just once, but when I refresh works. I resolve the problem moving cors in my nodejs API on top

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.