Encountering a 404 error when trying to retrieve parameters in Express JS

I am attempting to save a file by sending it as a JSON string through an ExpressJS POST request:

app.post('/filewrite/', (req, res) => {
  const fs = require('fs');
  console.log(req.body);
  fs.writeFile("./db/test.json", req.body, function(err) {
      if(err) {
          return console.log(err);
      }  
      console.log("The file has been saved!");
  }); 
});

However, when I try to send the data, I receive a 404 error message:

POST http://localhost:5000/filewrite/%7B%22db%22:[%7B%22ID%22:%2211111111%22,%22job%22:%2222222222]%7D 404 (Not Found)

What changes do I need to make in defining the POST route to accept parameters correctly?

Answer №1

If you wish for the data to be visible in req.body, then it must be included in the request body rather than the URL.

By attempting to include it in the URL, the route will not align properly.

I am unsure of what function POST serves, but if using cURL, you can achieve this by:

curl --header "Content-Type: application/json" \
     --request POST \
     --data '{"db":[{"ID":11111111,"job":22222222]}' \
     http://localhost:5000/filewrite/

Answer №2

Instead of passing the data in params, it is recommended to handle it differently. However, if you still prefer to pass it this way, here's a possible solution:

app.post('/filewrite/:data', (req, res) => {
  const fs = require('fs');
  console.log(req.body);
  fs.writeFile("./db/test.json", req.params.data, function(err) {
      if(err) {
          return console.log(err);
      }  
      console.log("The file was saved!");
  }); 
});

Keep in mind that writing data directly to a local file through the server may not be secure. Consider setting a static path for the folder or file. Here is a helpful resource: Save post data in local file

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

Limit the input to numbers when pasting into Angular

Implementing a directive in <input type='text'> to restrict user input to numbers has been successful! The issue arises when a user copies and pastes a string, causing Angular to accept the value and send it to the backend. angular.module ...

Node.js program closes immediately upon Java startup

I am building a Discord bot that features a Java FXML interface and utilizes a Node.js program to function as an Audio playing bot. However, I am encountering an issue where the process for Node.js closes immediately when opened in Java. The problem arise ...

Customize the position values of the Ngx-bootstrap Tooltip manually

I have incorporated ngx-bootstrap into my Angular 4 application. The component I am using is ngx-bootstrap Tooltip: After importing it, I am implementing it in my component's view like this: <button type="button" class="btn btn-primary" ...

Discover how to utilize Express.js with MongoDB using the forEach method

I am facing a major issue. I need to go through a collection of results and for each set, I need to find one specific result. This is how it currently looks: router.get('/', function(req, res) { var floors = []; var rooms = []; req ...

Using Javascript to target elements with identical attributes

I have some HTML similar to the code below: <form name="test_form"> <input type="hidden" name="product_id" value="560"> <input type="hidden" name="product_name" value="test product"> <input type="hidden" name="product_type" value="7"& ...

Error 400: Token Obtain Pair request failed in Django REST with simpleJWT and Vue 3 composition API

I'm encountering an issue with obtaining the refresh and access tokens when sending a form from my Vue app to the Django REST API. CORS has been enabled, and signing up through the REST API page or using Postman doesn't pose any problems. However ...

What methods can I use to modify strings within JSX?

Within a JSX file, I am faced with the task of manipulating a particular string in a specific manner: Imagine that I have the following string assigned to medical_specialty = "Plastic Surgery" The objective is as follows: medical_specialty.replace(&apos ...

"Collaborative Drive" assistance within Google Apps Script

Currently, I am developing a JavaScript tool within Google Apps Script to analyze various document properties such as the validity of links and correct permissions settings. To achieve this, I have been utilizing the API outlined in https://developers.goog ...

Using Javascript to retrieve information from a json file

I am currently working on incorporating JSON data into my script. I have noticed that when I manually declare a variable and check the console output, everything seems to work fine. <script> data = '[{"id": 1,"name": "Germany"},{"id": 2,"name": ...

What is the best way to achieve a partial match using JQuery?

I'm experimenting with this $("ul.nav-tabs a:contains('profile')").parent().addClass("active") It does not function properly if I include Profile in the text. Is there a way to make it case insensitive? ...

Trouble arises when trying to retrieve a simple JSON object directly from MongoDB

Can anyone help me with an issue I'm experiencing in my code? I have a function that successfully finds an object in my schema database and logs it correctly. However, when I try to access the object outside of the function, it returns as null. Any su ...

Tips for transferring information between routes in Node.js using Express.js

How can I add a specific attribute to the request object and access it from another route after redirection? Below is an example of what I am looking for: const express = require('express') const app = express() app.get('/test1',(req, ...

What would occur if the video I am currently uploading is deleted while the process is running in the background and being sent to the server?

As a mobile developer specializing in Android, I have a query regarding video uploading to the server. I am utilizing services in Android to upload the video in the background but I am faced with a doubt - what will happen if I delete the video while it ...

Utilizing AngularJS Directive to trigger a designated function upon change in an input file

My current project involves creating a scavenger hunt editor with various types of questions stored in an array. Each question can be of a different type, all displayed using ng-repeat. To achieve this, I utilize a JavaScript object representing a Questio ...

Submit the request again once the issue has been resolved in express.js

In my Express.js application, I often encounter the issue of the internal application changing its exposed connection port sporadically. Whenever a request fails, the next() function triggers an error middleware that checks and updates the internal applic ...

Tips on adding an item to the array field of a model in Mongoose

I have 2 collections like this: const vocaSchema = { word: String, type: String, meaning: String, sente: String, semean: String, sug: String }; const Voca = mongoose.model('Voca', vocaSchema); const setVocaSchema = { ...

Removing HTML elements and accounting for new lines in a text box

I am currently utilizing CodeIgniter for my personal website, which includes multiple textareas. I am looking for a solution to prevent HTML tags from being stored in the database. Is there a tool available that can strip out any unwanted tags? Additional ...

Include personalized headers to the 'request'

I have configured my express server to proxy my API using the following setup: // Proxy api calls app.use('/api', function (req, res) { let url = config.API_HOST + req.url req.pipe(request(url)).pipe(res) }) In this instance, confi ...

I am encountering an issue with retrieving API JSON data in NextJS where I am receiving an

Instead of receiving data in my console log, I am seeing undefined. This is my Index.js file (located in the pages folder) import Head from "next/head"; import Link from "next/link"; import axios from "axios"; import Test fro ...

Clicking on the current component should trigger the removal of CSS classes on its sibling components in React/JSX

Currently, I am working on creating a navigation bar using React. This navigation bar consists of multiple navigation items. The requirement is that when a user clicks on a particular navigation item, the class 'active' should be applied to that ...