weixin_33704234 2018-09-01 01:22 采纳率: 0%
浏览 671

为什么request.body为空?

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"
        })
    })
})
  • 写回答

1条回答 默认 最新

  • DragonWar% 2018-09-01 01:32
    关注

    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

    评论

报告相同问题?