0

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"
        })
    })
})
Omar Ali
  • 77
  • 1
  • 11
  • 1
    Possible duplicate of [req.body empty on posts](https://stackoverflow.com/questions/24543847/req-body-empty-on-posts) – Alexander Elgin Sep 01 '18 at 01:29
  • It seems that you do not use bodyParser at the back end. See https://stackoverflow.com/questions/43227729/express-js-req-body-returns-empty for more details – Alexander Elgin Sep 01 '18 at 01:30

1 Answers1

2

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

Shanil Arjuna
  • 1,135
  • 10
  • 18