Customizing response headers in vanilla Node.js

My Node.js setup involves the following flow:

Client --> Node.js --> External Rest API

The reverse response flow is required. To meet this requirement, I am tasked with capturing response headers from the External Rest API and appending them to Node.js's response header in order to send a single response header back to the client. This is how I attempted it (from the Node.js side):

var resHeaders = {
                    'Content-Type': 'application/json',
                    'Access-Control-Allow-Origin': '*',
                    'Access-Control-Allow-Methods': 'GET,PUT,POST,DELETE',
                    'Access-Control-Allow-Headers': 'Content-Type,Last-modified,Connection,Access-Control-Allow-Origin,Access-Control-Allow-Methods,Date',
                     'Access-Control-Expose-Headers': 'Content-Type,Last-modified,Connection,Access-Control-Allow-Origin,Access-Control-Allow-Methods,Date'
                 };

I have stored the External API's response header in a variable like so:

var curlHeadersResp; // Curl is used to retrieve response headers

My attempt to combine both responses looks like this:

var finalRespHeaders = new Array();
finalRespHeaders.push(curlHeadersResp);
finalRespHeaders.push(JSON.stringify(resHeaders));

res.writeHead(200, JSON.stringify(finalRespHeaders));

However, the resulting response header appears to be garbled:

HTTP/1.1 200 ["HTTP/1.1 200 OK\r\nServer: Apache-Coyote/1.1\r\nContent-Type: application/json\r\nTransfer-Encoding: chunked\r\nDate: Mon, 03 Feb 2014 09:25:06 GMT\r\n\r\n","{\"Content-Type\":\"application/json\",\"Access-Control-Allow-Origin\":\"*\",\"Access-Control-Allow-Methods\":\"GET,PUT,POST,DELETE\",\"Access-Control-Allow-Headers\":\"Content-Type,Last-modified,Connection,Access-Control-Allow-Origin,Access-Control-Allow-Methods,Date\",\"Access-Control-Expose-Headers\":\"Content-Type,Last-modified,Connection,Access-Control-Allow-Origin,Access-Control-Allow-Methods,Date\"}"] Date: Mon, 03 Feb 2014 09:25:38 GMT

This seems to be an issue with concatenation. I would appreciate any insights or solutions on generating dynamic headers in this context.

Why am I doing this? Due to cross-domain request obstacles, I lack control over the external server. Therefore, I must append Allow cross domain headers from my Node.js side to enable cross-domain requests.

Answer №1

According to the Node.JS Documentation:

//response.writeHead(statusCode, [reasonPhrase], [headers])
//                    number      string          object

var message = 'hello world';
response.writeHead(200, {
  'Content-Length': message.length,
  'Content-Type': 'text/plain' });

Avoid creating an array and pushing objects into it, instead merge the curlHeadersResp and resHeaders together:

Object.keys(curlHeadersResp).forEach(function (key) {
    resHeaders[key] = curlHeadersResp[key];
});

When setting the header, there is no need to stringify the object, simply use:

res.writeHead(200, resHeaders);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The jquery and operator fails to function

I am encountering an issue with the code snippet below. The functionality involves a button that toggles a div. Within this toggle div, there are several other divs and elements. $(function () { $('#btn').click(function (e) { e.preve ...

Create a vibrant PNG image background that changes dynamically based on the dominant color of the

Is it possible to dynamically set the background color of a PNG image, either white or black, based on the dominant color in the image? For example, this image should have a dark background: https://i.stack.imgur.com/cerjn.png And this one should have a ...

Utilizing the reduce method to transform an array containing nested arrays into a different structure

I'm having trouble figuring out how to restructure the array below. I attempted to utilize the reduce function in JavaScript but unfortunately, I couldn't make it work. So far, this is the function I have come up with: var comb = [] var setEle ...

I've been attempting to relocate a CSS element at my command using a button, but my previous attempts using offset and onclick were unsuccessful

I am trying to dynamically move CSS items based on user input or button clicks. Specifically, I want to increment the position of elements by a specified number of pixels or a percentage of pixels. Currently, I am able to set the starting positions (top a ...

Python Firebase POST request encounters an unexpected token in the position 0, signaling the end of the file

I am attempting to use Firebase to send a message to a specific client. The code I am currently using for testing is as follows: import json import requests import urllib def send_message(): server = "https://fcm.googleapis.com/fcm/send" api_key ...

Tracking tool for monitoring progress of HTTP POST requests

Hi, I am still a beginner when it comes to NodeJS and its modules. I could really use some assistance with creating a progress bar for an application I'm working on. Right now, the progress bar only reaches 100% upon completion and I suspect my piping ...

POWER QUERY - Data in a JSON request with incorrect structure

I have encountered an error while developing a request in Power BI's Power Query. The error message is as follows: Invalid format payload in a JSON request. Here is the code snippet: let URL1 = "example/login", POST = [ #"Conten ...

Is there a way to deliver information to a specific element on a client's HTML page?

My current project involves using Node.js to serve a webpage that collects user inputs and stores them in a mongodb server. The web page also displays these user inputs. I am trying to determine the best way to pass the user inputs from node.js to the < ...

Develop a program that retrieves necessary components, sets up, and launches a web browser

I am running an application with a node server and I want to achieve the following: npm start This should install both node dependencies and bower dependencies, and then open a browser window. Is it possible to do this without using gulp or grunt? Howe ...

Tips for retaining input field content within a BootstrapVue table

Below is a BootstrapVue table I'm working with; The code, courtesy of this response, is showcased below; new Vue({ el: '#app', data() { return { filter: '', items: [ { id: 1, first_name: "Mikkel&qu ...

What are the steps to effectively utilize my search bar alongside Google Custom Search?

Here is the HTML code for my form: <form action="#" class="searh-holder"> <input name="se" id="se" type="text" class="search" placeholder="Search.." value="" /> <button class="search-submit" id="submit_btn"><i class="fa fa-sea ...

Navigating JSON Data with ES6 Iteration

Issue Description There are two APIs I am working with. The first one, let's call it API #1, provides JSON data related to forum posts as shown below: [{ "userId": 1, "id": 10, "title": "Tt1", "body": "qBb2" }, { "userId": 2, ...

Uploading a Node.js Package to GitHub Packages - Issue ENEEDAUTH

Hello everyone, I am currently attempting to deploy my NPM package to GitHub packages using the following yaml configuration: # This workflow will run tests using node and then publish a package to GitHub Packages when a release is created # For m ...

Managing the inclusion of double quotes that are dynamically inserted using ajax and jquery

In this particular code snippet, the values of two input fields are being sent to another service via API. Everything functions as expected unless one of the input values contains a double quote ", which causes the API to return a 400 error (bad request) u ...

Encountering issues with link button redirection

I have a question regarding a Link element and CustomButton element with an onClick handler. < Link to = "/dashboard" style = { linkStyles } > < CustomButton text = "Login" onClick = { handleSubmit } /> < /Link> The code ...

What could be causing DEBUG to not output to the console?

I am currently learning about node.js and express through a tutorial. My issue lies with the debug feature not logging anything to the console, while console.log works perfectly fine. Despite being on Windows and attempting to run the app using "set DEBUG ...

Encountering difficulty installing a private npm package within GitHub Actions

Having a private npm package within my organization that is crucial for my project, I have encountered an issue while trying to build the project in a different repository. Despite successfully creating tokens and publishing the package from a separate wor ...

Sharing State with a Secure Route in Vue Router (using the script setup method)

Hello everyone, I'm encountering an issue while trying to send a state to the protected routes in vue-router. The error that I faced mentioned "Discarded invalid param(s) "_id", "dish_name", "description", "img" ...

Oops! The type 'List<dynamic>' cannot be assigned to the type 'Map<String, dynamic>'

I am currently working on retrieving additional information about users once they have entered their email and password. The API that I am utilizing returns extra user details, so my initial goal is to retrieve this information. My objective involves pars ...

Showing undefined or null values in React and JavaScript

My goal is to format undefined or null values by italicizing them. If the value is an empty string, it should be displayed as is. If it has a value, that value should also be displayed as is. However, I am encountering an issue where null or undefined val ...