Ad

Access Control Allow Origin Errors

- 1 answer

I am learning how to build APIs with Node.js. I was getting cors error when I try to fetch from my browser and my research tells me that, it is difficult to make a request on localhost unless the cors is disabled from the browser so I set up cors but I still kept receiving the error. Here is my app.js and routes.js file.

.............
app.use(cors());
app.use("/dashboard", dashboardRouter);
.............
// My routes
router.get("/api/inventory", function (req, res, next) {
    return new Promise(function (resolve, reject) {
        res.header("Access-Control-Allow-Origin", "*");
        if (req.header('Authorization') == 'Bearer test') {
            db.getFullInventory()
                .then(function (result) {
                    resolve(
                        res.json({
                            success: true,
                            data: result
                        }));
                })
                .catch(
                    function (err) {
                        reject(res.json({
                            success: false,
                            data: err
                        }));
                    }
                )
        } else {
            reject(res.json({
                success: false,
                data: "token is invalid"
            }));
        }
    })
});

Can someone explain to me, how to make my api compatible. Postman works though.

Ad

Answer

This looks like an express app.

Please use:

npm install cors

Then, where you setup your App use:

const app = express()
app.use(cors())

See Express CORS Documentation Here

For Modular Routing (which it seems like you're using) you may also need to add CORS to the modular routes.

E.g:

router.use(cors())
Ad
source: stackoverflow.com
Ad