Tips for transmitting data from the server to the client side

From the code posted below, I am attempting to transfer the value access_token from the method fetchAuthenticationToken to the method fetch in Ws.js. In fetchAuthenticationToken, I receive the value for the access_token and then assign that value to both resolve and onResult. So far, I can obtain the value of access_token successfully. This is all part of the .then() in the web-service called processor.

In the web-service processor, I use

.then(resp => {res.send(resp);})
to send the value of access_token to the front-end. However, the console output of fetch shows the following:

{"msg":"I.xx::fetch:http://localhost:3000/xx/processor/","response":{}}

which indicates an empty response

Please help me figure out what I missed and how to pass the value of access_token from the back-end to the front-end, specifically from fetchAuthenticationToken to fetch

setup.js:

fetchAuthenticationToken(onResult) {
    return new Promise((resolve,reject) => {
        this.#instance.post("/xx/xx/xx/xx/xx-xx/xx", this.#body, this.#config)
        .then(resp => {
            this.#access_token = resp.data.access_token;
            Object.assign(this.#instance.defaults, {headers: {authorization: `Bearer ${resp.data.access_token}`}})
            resolve(this.#access_token);
            onResult(this.#access_token);
        })
    });
}

routes.js:

router.post('/processor', async (req, res, next) => {
        let accessToken = null;
        const setup = new Setup();
        await setup.fetchAuthenticationToken((result) => {
            accessToken = result;
            res.setHeader('Content-Type', 'application/x-protobuf'); 
        })
        .then(resp => {
            res.send(resp);
        })
    });
    

front-end Ws:

fetch(onResult) {
    return new Promise((resolve, reject) => {
        const ws = endPointsURLs.VUE_NEWSWM_APP_LOCAL_HOST_3000.description + endPointsURLs.VUE_NEWSWM_APP_PATH.description + BackendWssConstants.CONST_WS_SENTINELHUB_ENGINE_PROCESSOR.description;
        fetch(ws, this.#requestOptions)
        .then(response => {
            this.#msg = JSON.stringify({msg:infoTag + 'fetch:' + ws, response: response});
            console.info(this.#msg);
            resolve(response);
            onResult(response);
        })
    });
}

Answer №1

When using the fetch function, remember that the response parameter you receive is not the JSON data itself. You must first call text() on it to get the actual content:

fetch(onResult) {
    return new Promise((resolve, reject) => {
        const ws = endPointsURLs.VUE_NEWSWM_APP_LOCAL_HOST_3000.description + endPointsURLs.VUE_NEWSWM_APP_PATH.description + BackendWssConstants.CONST_WS_SENTINELHUB_ENGINE_PROCESSOR.description;
        fetch(ws, this.#requestOptions)
        .then(response=>response.text())
        .then(response => {
            this.#msg = JSON.stringify({msg:infoTag + 'fetch:' + ws, response: response});
            console.info(this.#msg);
            resolve(response);
            onResult(response);
        })
    });
}

To simplify your code even more, it seems like the post() method in fetchAuthenticationToken already returns a promise, so there's no need to wrap it in another promise. Here's a more streamlined version of the code:

fetchAuthenticationToken() {
    return  this.#instance.post("/xx/xx/xx/xx/xx-xx/xx", this.#body, this.#config)
      .then(resp => {
        this.#access_token = resp.data.access_token;
        Object.assign(this.#instance.defaults, {headers: {authorization: `Bearer ${resp.data.access_token}`}})
        return this.#access_token;
        
    })
}

router.post('/processor', async (req, res, next) => {
    let accessToken = null;
    const setup = new Setup();
    await setup.fetchAuthenticationToken()
        .then(resp => {
        res.setHeader('Content-Type', 'application/x-protobuf'); 
        res.send(resp);
     })
});

Simplifying the code can make it easier to debug by removing unnecessary layers.

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

Set up mongoose using npm on a Windows operating system

As I embarked on a new project using node.js and mongodb, I realized that I required the mongoose package to interact with the database. However, I encountered difficulties in installing it. Is there anyone who has faced a similar issue and found a soluti ...

Angular input range slider that automatically rounds decimal values from the data bindings

I've implemented a range slider within an Angular form to capture and display recorded values. <input [formControlName]="object.id" [id]="object.id" type="range" [(ngModel)]="object.answer" [step]="objec ...

Utilizing Vue's data variables to effectively link with methods and offer seamless functionality

I am encountering difficulty retrieving values from methods and parsing them to provide. How can I address this issue? methods: { onClickCategory: (value) => { return (this.catId = value); }, }, provide() { return { categor ...

Is it possible to display a variety of color schemes in just one console.log()?

My task involves working with an array of hexadecimal values, "colors": ["#d5dd90","#e6bb45","#ef9770"] To log these out in different colors, I used the following method: colors.forEach((value)=>{ console.log(& ...

Ensure that the alert for an Ajax JSON record count remains active when the count is

Trying out Ajax JSON for the first time has been a bit tricky. Even though I hard coded "Record: 1" on the server side, it keeps alerting me with a total record of 0. I'm not sure where I went wrong. Could it be an issue with how I passed the array da ...

Searching for parameters wrongly triggering the id on a different route

Having recently delved into mongoose, I must apologize in advance for any misuse of terminology on my part. Below is the content of my routes file: const express = require('express'); const router = express.Router(); const passport = require(&a ...

Encountering issues with Ubuntu 16.04: Finding it difficult to resolve problems due to conflicting packages that are

I've attempted to uninstall and reinstall node.js multiple times in order to install npm. I gave Aptitude a shot to resolve dependencies but with no success, and considered using Synaptic Package Manager, although I'm unsure of the next steps. Th ...

What is the process of including a pre-existing product as nested attributes in Rails invoices?

I've been researching nested attributes in Rails, and I came across a gem called cocoon that seems to meet my needs for distributing forms with nested attributes. It provides all the necessary implementation so far. However, I want to explore adding e ...

The webpack-concat-text-plugin "node" is not compatible

The concat-text-webpack-plugin is located deep within a package, and it throws errors when I have NextJS and Node 18. Error: The engine "node" is incompatible with this module. Expected version ">=8 <=16". Got "18.16.0" Error Found incompatible modul ...

Steps to modify the servletRequest's content length within a filter

My main objective is to secure the POST body requests sent from my web application to my service by encrypting them. This encryption process takes place within a filter in my system. However, I've encountered an issue related to content length. When ...

Modify the length of an array using a number input field

Currently, I am working with an array that contains objects and I want to dynamically change the number of objects in this array based on user input from a number type input box. Whenever the number in the input box is increased, I need to increase the len ...

Efficiently perform complex nested grouping using the powerful array

Hi, I'm currently facing difficulties while attempting to utilize the array.reduce() function in order to achieve correct grouping for a specific scenario: Here is my original array: { { descriptionFunction: "Change", processDate: "201 ...

Tips for decreasing the width of a Grid component in React using MUI

Is there a way to adjust the width of the initial Grid element within Material UI, allowing the remaining 3 elements to evenly occupy the extra space? see visual example Would modifying the grid item's 'xl', 'lg', 'md', ...

Adjust the color of the entire modal

I'm working with a react native modal and encountering an issue where the backgroundColor I apply is only showing at the top of the modal. How can I ensure that the color fills the entire modal view? Any suggestions on how to fix this problem and mak ...

Unable to transfer the component between components

This is the code I have: index.js: import React from "react"; import ReactDOM from "react-dom"; import {dest, People} from './components/people'; import json from './people.json'; function initFromJson() { let names = []; for(let ...

Unable to retrieve data from the JSON file after making a $http.post call

Currently facing an issue with my grocery list item app developed in AngularJS. I have simulated a connection to a server via AJAX requests made to local JSON files. One of the files returns a fake server status like this: [{ "status": 1 }] I am att ...

Encountering an issue when attempting to send a post request with an image, resulting in the following error: "Request failed with status code

Whenever I submit a post request without including an image, everything goes smoothly. However, when I try to add an image, the process fails with an Error: Request failed with status code 409. Below is the code snippet for my react form page. const Entry ...

Tap the key in Robot.js in an asynchronous manner

I'm using robot.js to execute a high volume of key tap commands rapidly in my program. Here's a brief overview of how it currently works: ...for in elements setTimeout(() => { console.log(element.deltaTime) // Records the time that the k ...

What is the procedure for transferring the inputted data from an HTML file to its corresponding TS file and subsequently to a different component file?

I have created two components, a login and a home-page. I am attempting to capture user input from the login template, pass it to the login component, and then display it on the home-page template using the home-page component. What is the best approach to ...

Discover the significance of a data attribute's value for effective comparisons

I have a loop that generates random numbers and positions to create 4 answer choices for users. Now, I am trying to determine the value of the clicked button and compare it to the position of the correct answer. However, whenever I try to do this, it retu ...