简体   繁体   中英

Why would async function pass an empty object in request body?

I am using nuxt.js, mongoDB, express and bodyParser, too

So the other answers here won't help me for they say having bodyParser will fix it .

The uploadPet function is supposed to gather the form data, and send it to api as a post request. Appending formData is a success, this i can check in console, but then somehow in api.js the request is an empty object.

new.vue :

async uploadPet() {
  let formData = new FormData();   

  for (let data in this.pet) {
    formData.append(data, this.pet[data]);
  }
  for (var p of formData) {
      console.log(p);
    }
  try {
    console.log('trying to make a post request: ' + formData)
    let response = await fetch("http://localhost:9000/api/pet/new", {
      method: "POST",
      body: formData
    });
    this.$router.push("/");
  } catch (e) {
    console.error(e);
  }
}

api.js : (by now the request body has no data)

    router.post('/pet/new', (req, res) => {
    console.log('posting!')
    console.log(req.body.name)
    Pet.create({
        name: req.body.name,
        description: req.body.description
    }, (err, pet) => {
            if (err) {
                console.log('CREATE error: ' + err);
                res.status(500).send('Error')
            } else {
                res.status(200).json(pet)
            }
        })
    })

index.js :

    const express = require('express');
    const bodyParser = require('body-parser');
    const mongoose = require('mongoose') 
    const morgan = require('morgan');
    const api = require('./routes/api')
    const pets = require('./mock')
    const path = require('path');
    const app = express()

    app.use((req, res, next) => {
        res.header("Access-Control-Allow-Origin", "*");
        res.header("Access-Control-Allow-Headers", "Origin, X-Requested- 
           With, Content-Type, Accept");
        res.header("Access-Control-Allow-Methods", "GET, POST, PUT, 
            DELETE, OPTIONS");
        next();
    })
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: true }));

I already do have bodyparser concerning lines please don't recommend me that :

use this code in app.js because you don't parse req.body

const bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM