No responses received for my post on Node Express - a newbie in the world of Node

My current task involves utilizing an Axios post function to send multipart form data to a Node.js Express endpoint using Multiparty for input field processing.

Upon receiving the data, the endpoint saves it in the database. I am looking to utilize the response status to trigger a form.reset() upon successful completion.

How can I retrieve the response status within the post function?

Here is the code snippet for the listener and post:

let categories = []


const form = document.getElementById("category");
  
const formEvent = form.addEventListener("submit", async (event) => {
  event.preventDefault();
  let cat = new FormData(form);
  cat.append('userId',userId)
  await postCat(cat);
});

const postCat  = async (cat) =>{
   
    await axios.post('http://localhost:8080/api/category-api/addNew/?', 
         cat, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        }
      )
         .then( (res) => {
            if ( res.status(200)){
              form.reset();
              document.getElementById('shim').style.display = document.getElementById('msgbx').style.display = "none";
            }  
            else if (!res.status(200)) {
                  return null
              }
          })
          .catch((e) => {
              console.log('ERROR ERROR', e, 'ERROR ERROR')
          })
}

This section pertains to the endpoint setup:

router.post("/addNew/", async (req, res) => {

  let form = new multiparty.Form();

  let pros = [], cons = [];
  let newCategory = { pros, cons }

  await form.parse(req, async (err, fields) => { 
    await Object.keys(fields).forEach((property) => {
      
      if (fields[property].toString().length > 0 && fields[property].toString() !== ' ') {
        if (property.startsWith('pro')) newCategory.pros.push(fields[property].toString())
        else if (property.startsWith('con')) newCategory.cons.push(fields[property].toString())
        else newCategory[property] = fields[property].toString();
      }
      if (property === ('name') && newCategory[property].length === 0) {
        return res.status(400).json({ msg: "Name must be included" });
      }
    }
    )
    categories.push(newCategory)     //inside form.parse is the key!
    await insertCat(newCategory)           
    await res.status(200).json(categories) 
  })
});

I have tried using await insertCat(newCategory) and

await res.status(200).json(categories)
to ensure that insertCat completes before triggering res.status. However, it seems like the post method does not wait for the status. Is there a way to make it wait?

Thank you for your attention.

Answer №1

Do not use Axios's response.status as a function. Instead, try using res.status === 200 or consider keeping res.ok.

Answer №2

It was discovered that res.status(200) is not a valid function to use, however, utilizing res.status == 200 within the axios.post method proved to be effective.

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

React failed to render the information fetched from an API following a GET request made in componentDidMount()

I recently implemented a function in my React code that calls an API and updates the state based on the data it receives. getUserList() { API.get('/userlist') .then(response => { this.setState({ userLis ...

Ways to align backend timer with mobile application

In my app development process, I am working on a feature where a user is chosen and given a 15-second timer to respond. The app queries the database every 5 seconds to check if that specific user has been chosen. However, there's an issue with the syn ...

What is the best way to check for a matching array value in my menu list and apply a corresponding class tag to it?

I need a way to dynamically add a class to tags that match specific array values. My menu list consists of 150 items, and I want to add a class to the tag whose text matches an element in the array. <ul class="nav main" id="tabs"&g ...

JavaScript to enable button functionality for selected items

Currently, I am developing a To-Do List application. Once users input information, it gets displayed in a table format. My objective is to have the ability to select specific items from this table and apply various button functionalities to them such as ma ...

Creating a tree array in JavaScript from JSON data

I have been struggling to create a tree array from the given JSON data. I have attempted to use filter, map, and reduce methods, but haven't been successful in achieving the desired result. [{ "code": "2", "name": "PENDING" },{ "code": "2.2", ...

Is it possible to simultaneously run multiple functions with event listeners on a canvas?

I'm attempting to create a canvas function that displays the real-time mouse cursor location within the canvas and, upon clicking, should draw a circle. I came across this code snippet that reveals the x and y coordinates of the mouse: document.addEve ...

Use the evernote findNotesMetadata function to efficiently retrieve all notes by implementing an offset and maxnotes parameter for looping through

According to the documentation provided by Evernote regarding findNotesMetadata, the maximum number of notes returned from the server in one response is 250. I am currently exploring how to handle multiple requests in order to retrieve the entire array if ...

Is it possible to utilize a function as a route-handler?

I've developed a RESTful API with a rendering function that's structured like this: render = (req, res) => { var output = {}, async = [], detailed; if(req.user){ detailed = req.user.obj.detailed(); asy ...

Mapping through an undefined array in React causing an error: "map of undefined"

To display an image, title, and description in the browser, the data is stored in an array in a file named customData.js. Below is an example of the data structure: var DATA = [ { name: 'John Smith', imgURL: 'http://whi ...

Multer ensures that all fields are validated before proceeding with the upload process

I have been trying to implement field validation before uploading in NodeJS using Multer, but it doesn't seem to be working. I spent days on this issue and still couldn't get it to work. Is it possible that Multer doesn't support this featur ...

Placing a div on top of a link renders the link unusable

I am facing a situation and require assistance (related to HTML/CSS/JS) I currently have a div containing an image (occupying the entire div space) such that when hovered over, another div with an image is displayed on top (the second div is semi-transpar ...

In a perplexing twist, requests made to the Express app arrive with empty bodies despite data being sent, but this anomaly occurs

Welcome to the community of inquisitive individuals on Stack! I'm facing an interesting challenge while developing an Express app. Despite everything running smoothly with two routes, I've hit a roadblock with one route that seems to have empty i ...

Expressing HTTP 403 error and rendering with Node.js

Is it possible to display a customized error message with an error 403 status? Currently, the code I have is: res.send(403,"You do not have rights to visit this page"); However, I would like to show a HTML page instead of just plain text. res.render(&a ...

JavaScript to resize images before uploading without displaying a preview

I'm searching for a way to prevent the need to upload large or heavy image files. I believe utilizing the HTML5 FileAPI library is the best solution for this task. All necessary features have been implemented (upload, re-ordering, etc.), so now I ju ...

The tooltip feature in jQuery is experiencing some stuttering issues

Sometimes, images can convey messages better than words. I encountered a strange issue with my self-made jQuery tooltip. I prefer not to use any libraries because my needs are simple and I don't want unnecessary bloat. When I move my mouse from righ ...

What is the importance of manually merging geometries?

After exploring the performance implications of merged geometries, I've discovered that the GPU generates draw calls for all shared geometries combined with materials (or maybe just the material count). This has led me to wonder why developers are req ...

Sending data to a MySQL database using AJAX with PHP

While attempting to use ajax to insert a value in PHP, I am encountering an issue where the data is not getting inserted into the database. The code snippet I am using was sourced from answers provided on this site. Can someone please point out where I m ...

Navigating to the bottom of a specific element by scrolling

I am currently working on enhancing a module within the application I'm developing. The goal is to automatically scroll the browser window to the bottom of an element when said element's height exceeds the height of the window. The functionality ...

What is the best way to transfer information from JavaScript to a JSON database using the fetch API?

Within the userDB.json file, it appears as follows; [{ "username": "john", "xp": 5 }, { "username": "jane", "xp": 0 } ] Inside the app.js file ; async function getUsers() { le ...

Excessive iterations occurring in JavaScript for loop while traversing an array

After addressing the issues raised in my previous inquiry, I have made significant progress on my project and it is now functioning almost exactly as intended. The main purpose of this website is to iterate through the World Of Tanks API to generate cards ...