Issue with Post request from fetch causing a server error (javascript/express)

Currently, I am experimenting to determine if a POST request will function correctly on my server through the '/db' route. Surprisingly, while the GET request is successful, the POST request consistently results in a '404 - not found' error.

To illustrate, here is a portion of my JavaScript code:

function getReq() {
    let p = fetch("http://localhost:3000/db").then((a)=>a.json()).then((x)=>console.log(x))
}

async function postReq(obj) {
    console.log(obj)
    const p = await fetch("http://localhost:3000/db",
        {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: obj
        }
    )
}

This snippet shows my Express code:

const app = express();
app.use(bodyParser.json());

app.get('/db', (req,res)=>
{
    res.sendFile("db.json");
});

app.post("/db", function(req,res) 
{
    res.send("ok");
});

app.use(express.static('public'));
app.listen(3000, (ok) => console.log("Okk"));

Both db.json and app.js exist within the same folder, with only JSON strings being passed into postReq. Additionally, all other files are located in the 'public' directory. I would greatly appreciate some guidance on what might be causing this issue. Thank you in advance.

Answer №1

Make sure to convert the body to a string since your content-type is set to application/json

async function sendPostRequest(dataToSend) {
        console.log(dataToSend)
        const response = await fetch("http://localhost:3000/db",
            {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify(dataToSend) // Ensure conversion 
            }
        )
    }

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

Dividing blocks of text into individual sentences

Seeking a solution to splitting a paragraph into individual sentences, I initially attempted the following code: var sentences = paragraph.split('.'); While this method was effective in most cases, it encountered issues with sentences like: ...

What is the best way to transfer properties to a different component using the onClick event triggered by an element generated within the map function?

I am currently working on an application using react to retrieve data from a mongodb database. Within one of the components, called Gallery, I have integrated a map function to display a list of items. My goal is to implement an onClick event for each elem ...

Warning in Next.js: When utilizing conditional rendering, the server HTML is expected to have a corresponding <div> inside another <div>

Although similar questions have been asked on various platforms like Google, none seem to provide answers that align with my specific situation. Essentially, my goal is to have a different search bar displayed in the header based on the page I am currentl ...

Dynamic linked selection

Basic selection Segment Selection Category selection The choice of one parameter affects the options available in another section, with subjects depending on segments. If a subject is selected, only assignments related to that specific subject will b ...

Managing a significant volume of form data transmission to PHP backend

I have a moderately large HTML form with Javascript functionality to dynamically create additional 'records' within certain sections of the form. There could potentially be over 50 INPUT elements in total. I am contemplating the most effective a ...

What is the best way to retrieve user interaction data in Discord.js v13?

Is there a way to retrieve the activities from interaction.options? Whenever I try using interaction.options.getUser, I encounter this error message: cannot read properties of undefined (reading 'activities') Below is the snippet of my code: con ...

Error: The function res.setHeader was not recognized, causing an issue when enabling CORS

I have encountered numerous similar issues but have not been successful in resolving this one. My primary goal is to send a JSON file from the client side via an API request to the server for storage in the database. However, since my frontend and backend ...

The operation cannot be completed because the property 'HmacSHA256' is undefined

I'm attempting to encrypt an ID for use as parameters in Vue.js using Crypto-JS, but I keep encountering the error message: Cannot read property 'HmacSHA256' of undefined. I ran into the same issue when trying ASE and MD5. What am I doing wr ...

"An 'undefined' message appeared on the server console following the completion of the

I developed a basic HTML application using Node.js. Below is the code snippet from server.ts: import express = require('express'); import http = require('http'); import path = require('path'); import cookieParser = require(& ...

Issues arise when using ng-repeat in conjunction with ng-click

I am facing some new challenges in my spa project with angularjs. This is the HTML snippet causing issues: <a ng-repeat="friend in chat.friendlist" ng-click="loadChat('{{friend.friend_username}}')" data-toggle="modal" data-target="#chat" d ...

Running a Javascript command in Selenium to extract information from a website

<h4>Lotus</h4> My goal is to extract the value of Lotus from the h4 tag. In a previous post, I found a solution using a JavaScript command: document.getElementById('17285').getElementsByTagName('h4')[0].innerHTML; This wo ...

Tips for creating a unique exception in AngularJS?

I have a customException.js script with the following service: app.service('CustomException', function() { this.CustomException1 = function (message) { if (!message) { message = "Custom Exception 1 occurred!"; } return { ...

Unexpected rejection of a promise, despite my confidence in having addressed all of them

I have created a node application that retrieves data from an API using various endpoints. To achieve this, I am utilizing proxies. Currently, I am employing socks-proxy-agent to establish an https agent for my axios instances in order to use the proxy. ...

Sorry, the OAuth2 Access Token for Discord with the grant type of 'None' is not compatible

I am currently working on implementing a Discord login system for my website using Express. I have created a function to retrieve an access token, which I aim to utilize in the route. The access token is being obtained from: Below is the code snippet: ...

The execution of a nested object's function that calls a JavaScript function encounters an error

Below is a simple example demonstrating the issue I am facing, which you can also view on JSFiddle here. While I understand why the issue is happening, I'm unsure of how to resolve it without altering the existing JS structure. The problem arises wh ...

Angular Xeditable grid defaults to the current date as the initial date

Currently, I am utilizing the Angular Xeditable grid found at this link. I am looking for guidance on how to set the current date as the default date on the calendar control that is integrated within the grid mentioned above. Thank you in advance. < ...

Conditional Matching with Javascript Regular Expressions

My strings are formatted like this: #WTK-56491650H #=> want to capture '56491650H' #M123456 #=> want to capture 'M123456' I am trying to extract everything after the # character, unless there is a dash. In that case, I onl ...

sequentially animating elements using animate css in a choreographed manner

I have created a unique jsfiddle with 20 boxes that I am trying to animate using the Animate.css plugin. The plugin can be found at daneden.me/animate. My goal is to animate each box one after the other in a sequential manner, but I seem to be having trou ...

What advantages does incorporating a prefix or suffix to a key provide in React development?

Is there any advantage to adding a prefix or suffix to the key when using an index as a key in React (in cases where no other value such as an id is present)? Here's an example: const CustomComponent = () => { const uniqueId = generateUniqueId( ...

Sending information to a personalized mat-grid element using properties

I am currently working on enhancing the functionality of the angular material mat-tree component by building a custom component. The main objective is to create a table with expandable and collapsible rows in a hierarchical structure. I have managed to ach ...