Is it possible to both retrieve and create data within the same route?

My route setup is like this:

 app.all("/checkoutupdateprods", async (res,req, next) =>{
  
  const url = GRAPHQL_CUSTOM_URL;
  console.log("in b_server.js", res.body);
  
  let data = res;

  await fetch(url, checkOut_ProductsInStock(data.body))
    .then(res => console.log(res.json()))
    .catch(err => req.send(err));
});

When initiating the process from the client side, I send a JSON string to the server. Subsequently, I generate a GraphQL query using this JSON string containing necessary IDs. The said query along with the URL is then used to make a GET request to Shopify in order to retrieve the required products.

This is why I have opted for utilizing app.all(), enabling me to perform both POST and GET actions within a single route. However, I am currently facing an issue where the response (res) is being assigned the POST JSON string from the client rather than the anticipated outcome from Shopify regarding the necessary products.

I am seeking suggestions on how to address this concern. Any advice?

EDIT**--- I have made adjustments as follows, but I am encountering a situation where the promise remains pending without resolution.

app.post("/checkoutupdateprods", async (req,res, next) =>{
  
  const url = GRAPHQL_CUSTOM_URL;
  console.log(req.body);
  
  let data = req;
  
  await fetch(url, checkOut_ProductsInStock(data.body))
    .then(res => console.log(res.json()))
    .catch(err => res.send(err));
});

Answer №1

The reason for the promise pending issue is due to the redeclaration of the res variable within the fetch promise chain.

app.post("/checkoutupdateprods", async (req, res, next) =>{

const url = GRAPHQL_CUSTOM_URL;
  console.log(req.body);
  
  let data = req;
  
  await fetch(url, checkOut_ProductsInStock(data.body))
    .then(response => response.json())
    .then(resultData => {
        console.log(resultData);
        res.json(resultData);
    })
    .catch(error => res.send(error));
});

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

Using AngularJS to add an element to an array based on a specified condition

dashboardCtrl Data app.controller('dashboardCtrl', ['$scope','$rootScope', function ($scope, $rootScope) { //Color $scope.Color = [{ colorname: "Red", number: "(3)" }, { colorname: "Brown ...

Leveraging the httponly cookie for transmitting JWT token between a Node REST API and a Vue.js SPA

I am currently in the process of developing a web application that utilizes a Vue.js frontend along with a Node REST API built using express. I am facing a challenge in implementing authentication, particularly in striving for a stateless approach by utili ...

Arranging date and time in jQuery based on AM/PM notation

I have written some JavaScript code to sort dates in ascending order (from newest to oldest). I have successfully sorted the dates, but I am having trouble sorting the time with AM or PM using a 12-hour format. I can do it in a 24-hour format, but not in ...

Can you explain the purpose of this variable "guess = require('myModule1')('myModule2');" ?

While examining a code snippet, I stumbled upon this line and am unsure which instance it is referring to. var guess = require('myModule1')('myMmodule2') ...

Issue with ForwardRef component in Jest for React Native testing

When attempting to write a test case for my Post Detail screen, I encountered an error that stated: error occurred in the <ForwardRef> component: Here is my test class code: import React from "react"; import { NewPostScreenTemplate } from ...

From JSON to HTML: A seamless transformation

Is there a way to convert a JSON object into HTML? I am currently making a get request that returns a JSON object with "_bodyText" as the key and the corresponding HTML string as its value. However, when trying to parse the JSON using JSON.parse(response), ...

Tips on inserting a script prior to the body tag

It appears to be a straightforward process, but I am struggling to figure out what I am missing: var string1 = document.createElement('script'); $(string1).attr('type', 'text/javascript'); $('body').before($(string ...

Ajax request mistakenly interprets empty data as containing [ ] symbols

I am experiencing an issue with my code that retrieves all posts. Even when there are no posts available, the data being sent is still [], which means that no errors are occurring even when the data is empty. As an example, the result is always ["Hello"], ...

Selenium aids the driver in locating elements

Currently working on Java programming. Here is a snippet of web code I am dealing with: <button class="btn-link" data-sugg-sources="full_name" data-sugg-technik="make_initial_and_name">NG1ulkan</button> When I right-click and copy the CSS sel ...

Having trouble using angular.isString in conjunction with ng-repeat

Is there a way to use angular.isString for comparison within an ng-if in an ng-repeat loop? Currently, all items in the array are being returned. I attempted to simply display the result of angular.isString, but no output is generated. This is my desired ...

The requested resource in Angular 5 does not have the 'Access-Control-Allow-Origin' header present

I am currently utilizing angular 5 and attempting to execute the following web service getMethod() { let headers = new Headers(); headers.append('Access-Control-Allow-Origin', '*'); headers.append('Access-Control-Allow-Methods&ap ...

Utilizing AngularJS in conjunction with Asp: UpdatePanel

<%@ Page Title="" Language="C#" MasterPageFile="~/Admin/AdminMasterpage.master" AutoEventWireup="true" CodeBehind="ExamSet.aspx.cs" Inherits="demo.Admin.ExamSet" %> <asp:Content ID="Content1" ContentPlaceHolderID="content" runat="server"> <s ...

Modify the Navbar color with a sticky-top effect in Bootstrap 4

For my sticky navbar, I utilized the Bootstrap 4 class sticky-top. My preference is for a CSS-based solution rather than JavaScript due to past errors encountered with JS. I aim to have my navbar change to a transparent color when it becomes sticky upon s ...

Obtain the specific key's value from a new Map state

In my code, I've defined a variable called checkedItems as a new Map(); When I try to console.log(checkedItem), the output is as follows: Map(3) {"1" => true, "1.5" => true, "2" => false} Is there a way ...

What could be causing the discrepancy between the assigned value in the UI and the value of the ref object, even though they appear to be the same in the console when viewed in the useEffect hook

By the end of the useEffect, inputValue is stored in previousInputValue.current. Since the useEffect runs during rendering or rerendering, I expected the value of previousInputValue.current in the second <h2> tag to be the same as inputValue. How is ...

Node.js - efficiently managing multiple arrays

I need assistance with handling different scenarios in a post creation process. The post can contain text, images, videos, and tags as options. Text is mandatory while the rest are optional. Using async, I want to know how to handle the following cases: ...

Utilizing C in WebAssembly to return string values

Is it possible to retrieve a JavaScript string from a WebAssembly function? https://dev.to/azure/passing-strings-from-c-to-javascript-in-web-assembly-1p01 - not functional C #include <stdio.h> #include <string.h> void jsPrintString(const ch ...

The Jquery onclick function is executing multiple times, with each iteration increasing in

I have encountered an interesting problem that I can't seem to resolve. The issue involves dataTables and the data that is retrieved via jQuery ajax post after a selection change on a select element. Furthermore, I have an onclick function for multipl ...

Which JQuery plugins can transform regular <select> dropdowns into more stylish options?

After an extensive search, I was only able to locate one solution at this link. I scoured the entire internet for alternatives. ...

Adding new options to a multi-select dropdown in Vue.js when fetching data using an

Greetings! I've been utilizing a modified wrapper to manage a multiple select for vue.js. My goal is to change the value of 'this' inside the vue component. Below is the snippet of my code. <select2-multiple :options="car_options" v-mode ...