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

What is the best way to ensure an observable has finished before retrieving a value?

Looking at the function provided below: public getAssemblyTree(id: number) { .... const request = from(fetch(targetUrl.toString(), { headers: { 'responseType': 'json' }, method: 'GET' })); request.sub ...

Managing a variety of users within a Node.js Express application

Exploring the world of NodeJs, I am embarking on the journey of constructing a blogging API using node and express. Seeking guidance on implementing the following tasks : Users can view other user's profiles, but cannot make edits. Users can read any ...

Leverage es6 classes along with mongoose in typescript to utilize loadClass functionality

I've been struggling with a problem and despite my exhaustive search on Google, I still haven't found a solution. My issue revolves around incorporating es6 classes with mongoose using the schema.loadClass(class) method. Unfortunately, when worki ...

Why is the Axios instance/function not being passed the argument?

I am currently working on refactoring a next.js App that has a functioning axios call. However, I have encountered an issue with my new function not receiving arguments. The problem consists of two main components: my next.js page and an external custom m ...

How can you deactivate the vue-router for specific routes? Is it possible to operate a single-page application backend while utilizing a non-single-page

I'm currently working on a website/webapp using Laravel 5.3 and Vue 2. Since SEO is crucial, I've decided to keep the frontend/crawlable part of the site in Laravel + Blade, with only minimal sections in Vue 2.0. This way, I can avoid using Ajax ...

Python makes it easy to print output from a REST API with efficiency

I'm using GET requests to retrieve and summarize data from a software system. While I have successfully extracted values from the REST API output and created a basic for loop to summarize it, I am struggling to present the information in a clear forma ...

Spin an object around the global axis using the tween.js library

I'm trying to achieve a gradual rotation of a cube on the world axis using tween. Initially, I was able to rotate the cube around the world axis without tweening with the following code: rotateAroundWorldAxis(cube[1], new THREE.Vector3(0,1,0),degreeT ...

What are the steps to incorporate PointerLockControl in Three.js?

Having trouble correctly integrating the PointerLockControl in Three.js? Despite trying various examples, errors seem to persist. I've been importing libraries through the head part like this: <script src="lib/controls/PointerLockControls.js"> ...

Unable to access Form element in Firefox browser

I'm struggling with debugging unfamiliar problems. For instance, in my HTML there's a form: <form name="myForm" > <table> <tr> <td> <input type="radio" name="myType" value="val" onclick="someF ...

Is it possible to convert a string of elements in JavaScript into JSON format?

Within my JavaScript code, a variable holds the following information: url=http://localhost quality=100 tag="4.4, 5.5" I am interested in converting this data to JSON format using JavaScript, like this: "result": { "url": "http://localhost", "qu ...

eliminating list item from unordered list depending on the input of either first or last name

My objective is to refine a lengthy list as the user types in a search for a specific person by first or last name. The current code I have functions adequately, but encounters an issue when there is a space in the input field. My goal is to allow users to ...

Transforming a REST API get call into GraphQL

I'm currently using a REST API that accepts a code parameter, searches the database for matches, returns results if the parameter exists, and redirects users to a long_url retrieved from the database. How can I convert this functionality to GraphQL? i ...

Change the name of the key in a JSON file with the help of Python

I need to change the name of a key in my JSON file. The structure of the objects in the file is as follows: [{"marka": "تويوتا" , "tag" : "MANF"}, {"marka": "شيفروليه" , "tag" : "MANF"}, {"marka": "نيسان" , "tag" : "MANF"}] My goal is ...

Navigate a user upon completion of an update

My webpage requires users to click an update link, which triggers a process of fetching data from an API that takes a few minutes. I don't want users to have to constantly refresh the page to know when the process is complete and they can continue. Is ...

Clicking on the button will instantly relocate the dynamically generated content to the top of the page, thanks to Vue

Here is some dynamically generated content in the left column: <div v-for="index in total" :key="index"> <h2>Dynamic content: <span v-text="index + ' of ' + total"></span></h2> </div> There is also a butt ...

When setting a value through the DOM, the input's value bound with ngModel in Angular does not get updated

Trying to upload a file to calculate its hash and display it in an input box. If done correctly, the value should show in the form, but when submitting the form, the value does not get sent. Only adding a blank space by clicking on the input field works: ...

This error is thrown when trying to access the property 'message' of an undefined value

I'm currently working on adding an AJAX contact form to my website. However, I've run into a problem where when I try to submit the form, I encounter the following error in Google Chrome: "Uncaught TypeError: Cannot read property 'message&a ...

TypeScript does not recognize the $.ajax function

Looking for help with this code snippet: $.ajax({ url: modal.href, dataType: 'json', type: 'POST', data: modal.$form.serializeArray() }) .done(onSubmitDone) .fail(onSubmitFail); ...

Issue encountered during Nuxt installation: A rule can only contain one resource source, which consists of the provided resource and the test + include + exclude

After successfully installing Vue.js and Node.js, I encountered an issue while trying to install Nuxt.js. Here is the error message that I received. Despite asking for help from friends, the problem still persists. Any assistance would be greatly appreciat ...

The for loop is throwing an error because the variable 'i' is not defined

I recently started using eslint and I'm in the process of updating my code to comply with my eslint configuration. module.exports = { env: { browser: true, commonjs: true, node: true, es2021: true, }, extends: 'eslint:recomm ...