简体   繁体   中英

Why is request.body is empty?

I have been building a simple blogging app using the Mean stack and I seem to struggle, the request.body is always empty even though I send data here's the code and the request is always pending in Chrome network tab till it gives Err_connction_refused or something like that and notice that I pass form data to the service which is where the problem lies

The Register service

import { Injectable } from '@angular/core';
import {Http, Headers} from '@angular/http';
import { map } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class RegisterService {

  constructor(private http: Http) { }
// A form data is passed as an argument to this function
      register(user) {
        let headers = new Headers();
        headers.append("Content-Type", "multipart/form-data")
        return this.http.post("http://localhost:3000/api/users/register", user, {headers})
        .pipe(map(res => res.json()))
    }
}

The routes in the server side-side (side-note: don't worry about the req.file.path)

// Registering a user
router.post("/register", upload.single("profileImage") , (req, res) => {
    let newUser = new User({
        username: req.body.username,
        password: req.body.password,
        email: req.body.email,
        name: req.body.name,
        bio: req.body.bio,
        interests: req.body.interests,
        profileImage: req.body.path
    })
    User.addUser(newUser, (err) => {
        if (err) return err;
        res.send({
            success: "true",
            msg: "You've logged in sucessfully"
        })
    })
})

1st step npm i body-parser

after installing the module add the below code to your app.js

var bodyParser = require("body-parser");

app.use(bodyParser.urlencoded())


app.use(bodyParser.urlencoded({
  extended: true
}));

Edit

used URL is http://localhost:3000/api/users/register

But Your Route is only /register .

your route and passed URL should match

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