DEV Community

Cover image for How to set multiple headers on nodejs express server response
Ifeanyi Chima
Ifeanyi Chima

Posted on • Updated on

How to set multiple headers on nodejs express server response

Let me start by saying, I respect Dave Gray a lot, he is the greatest Youtube tech creator out there. I really admire his method of project-based learning.

BMC

This tutorial is in reference to his nodejs_tutorial where he creates a REST API.

One day, I was working on a MERN stack application, as part of a side-project, and I kept on getting this error.

cors error

After some research, I came up with a solution.

When working with Node.js, you need to set the headers on the servers response.




// middleware/credentials.js


const allowedOrigins = require("../config/allowedOrigins");

const credentials = (req, res, next) => {
    const origin = req.headers.origin;
    if (allowedOrigins.includes(origin)) {
        res.set({
            "Access-Control-Allow-Origin": origin, // ==> new header
            "Access-Control-Allow-Credentials": true
        })
    }
    next();
}

module.exports = credentials



Enter fullscreen mode Exit fullscreen mode

The error is caused because the header Access-Control-Allow-Origin was not present. This header allows the origin (host) that made the request to be able to access the servers' resources.

The second header Access-Control-Allow-Credentials is used whenever a request is made with cookies to the server.

I learnt how to set multiple headers from this post

Reference

difference between setHeader and header

Summary

I tried to show you how to set multiple headers on the server's response.

Thank You

Follow me on twitter, github and linkedin

Buy Me A Coffee

Top comments (0)