Home > OS >  Frontend to Backend POST request is not yielding the data I want
Frontend to Backend POST request is not yielding the data I want

Time:08-27

I'm currently working on a project using a React frontend and an Express backend. Currently, when I make a GET request to retrieve data from the backend, everything is working fine. However, I'm unable to POST data to the backend and gain access to the data that's being sent. I'm getting an OK message so the request is going through, but when I log the request data in the backend, I get a message like this which is a jumble of random fields.

Here is the code snippit in the front end for the POST request

const makePost = (data) => {
        fetch('http://localhost:5000/api', {
            method: 'POST',
            headers: {"Content-Type": "application/json", "Access-Control-Allow-Origin": "*"},
            body: JSON.parse(JSON.stringify(data))
        }).then(function(response){
            console.log(response.text())
        })
        
    }

Here is my backend which handles the POST request

 const express = require('express');
 const app = express();
 const cors = require('cors');
    
 app.use(cors({
   origin: '*'
 }));
    
 app.get('/api', (req,res) => {
   res.json(menuItems);
 });
    
 app.post('/api', (req,res) => {
   console.log(req)
 })

app.listen(5000, () => console.log("server started on port 5000"));

In the code snippit above, console.log(req) is what was logged in the screenshot linked above.

CodePudding user response:

In your Express server POST API, you are not returning any data, it may cause problems. This is a sample POST API using Axios, Express, React, and MongoDB.Hope it would help you.

  //POST API
 app.post('/services',async(req,res)=>{
    const service = req.body;
    const result = await servicesCollection.insertOne(service);
    console.log(result);
    res.send(result)
 });
In client-side POST api:
 const onSubmit = data => { 
         axios.post('http://localhost/services', data)
                     .then(res=>{
                                if(res.data.insertedId){
                                alert('data added successfully');
                                reset();
                       }
                     })

sample post API:

app.post('/book', (req, res) => {
    const book = req.body;

    // Output the book to the console for debugging
    console.log(book);
    books.push(book);

    res.send('Book is added to the database');
});

Pls take a look at this link: https://riptutorial.com/node-js/example/20967/post-api-using-express

  • Related