DEV Community

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

Posted on • Edited on

3

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

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay