Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
360 views
in Technique[技术] by (71.8m points)

reactjs - When creating a MERN application, I need to create a POST request from frontend to the backend, but the request body is empty

I am creating a MERN application, where I am trying to send a post request to my backend, however when i log the req.body from my backend, it is empty

const removeTour = (id) => {
    const getDevices = async () => {
        const settings = {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ name: 'here', info: '1', image: '1', price: '1' })
        };
        try {
            const fetchResponse = await fetch(`http://localhost:3080/add-tour`, settings);
            const data = await fetchResponse.json();
            return data;
        } catch (e) {
            return e;
        }
    };
    getDevices();
    const newTours = tours.filter((tour) => tour._id !== id);
    setTours(newTours);
};

The function is called when the button is pressed. On the backend, i have an app.post, which should receive the request. THe request.body received is empty

const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const cors = require('cors');
require('dotenv').config();
const data = require('./data.json');

//dotenvs
const DBLink = process.env.DB_HOST;
const port = process.env.PORT;
const home = process.env.HOME;

//app
const app = express();
app.use(cors());
app.use(bodyParser.urlencoded({ extended: true }));

//shema
const TourSchema = mongoose.Schema({
    name: {
        type: String,
        required: true
    },
    info: {
        type: String
        // required: true
    },
    image: {
        type: String
        // required: true
    },
    price: {
        type: String
        // required: true
    }
});
const Tour = mongoose.model('tour', TourSchema);


//app routes
app.get('/', (req, res) => {
    (async () => {
        const tours = await Tour.find((data) => data);
        try {
            res.json(tours);
        } catch (error) {
            console.log(error);
        }
    })();
});
app.post('/add-tour', (req, res) => {
    console.log(req.body);
    // const { name, image, info, price } = req.body;
    // const tour = new Tour({ name, image, info, price });
    // tour.save();
    // res.status(201).redirect('http://localhost:3000/');
    res.send('here');
});

//mongoose
mongoose
    .connect(DBLink, {
        useCreateIndex: true,
        useFindAndModify: false,
        useUnifiedTopology: true,
        useNewUrlParser: true
    })
    .then(() => {
        app.listen(port, () => console.log(`Server is running on ${port}`));
    })
    .catch((err) => console.log(err));

All i get in the terminal is - terminal: {}

However when i am making a post request from a html form, with input that has a value and a name, the received request has the body

question from:https://stackoverflow.com/questions/65901415/when-creating-a-mern-application-i-need-to-create-a-post-request-from-frontend

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

Please log in or register to reply this article.

OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...