简体   繁体   中英

Getting back empty response body when making a POST request using Angular + Express

I'm trying to make a simple POST request but I'm getting an empty response back from the server. I've sifted through all the SO questions regarding this topic and tried the solutions posted but to no avail.

I've tried changing the request header options to use 'application/x-www-form-urlencoded' and set bodyParser in my express app as app.use(bodyParser.urlencoded({ extended: true })); but that didn't work either.

auth-service.service.ts

login(loginInfo: object) {
    return this.http.post<loginInfo>(this.loginUrl, { "test": "test" })
    .pipe(
        catchError(this.handleError)
    );
 }

 private handleError(error: HttpErrorResponse) {
    if (error.error instanceof ErrorEvent) {
       console.log('An error occured:', error.error.message);
    } else {
       console.log(`Backend returned code ${error.status}, ` +
      `body was ${error.error}`);
    }

    return throwError('Something bad happened; please try again later.')
 }

login.component.ts (calls the login service method)

onSubmit() { 
    const loginInfo = { username: this.username.value, password: this.password.value };
    this.authService.login(loginInfo).subscribe(
         resp => { console.log(resp); },
         err => { console.log(err); }
  )
}

server.js (I've defined routes here but they're not relevant)

const express = require('express');
const bodyParser = require('body-parser');
const api = require('./routes/api');

const app = express();
const port = process.env.port || 3000;

app.use((req, res, next) => {
     res.setHeader('Access-Control-Allow-Origin', '*');
     next();
})
app.use(bodyParser.json());

app.use('/api', api)
app.get('/', function (req, res) {
     res.send(JSON.stringify('Hello from server'));
})

app.post('/login', (req, res) => {
     let userData = req.body
     res.send('Request body: ' + JSON.stringify(userData));
})


app.listen(port, function () {
     console.log('Server running on localhost: ' + port);
 });

I'm console logging the following:

Backend returned code undefined, body was undefined

Something bad happened; please try again later.

When I try using Postman, however, I get the response I expect (ie Request body: {} )

I'm not sure as to why a response is retrieved when done through Postman but not when done through the app.

Any help is appreciated. Thanks!

You need to set body for POST request in auth-service.service.ts :

import { HttpParams } from '@angular/common/http';

login(loginInfo: object) {
  const body = new HttpParams()
    .set('test', 'test');
  return this.http.post<loginInfo>(this.loginUrl, body)
    .pipe(
      catchError(this.handleError)
    );
}

try using express.json its missing

app.use(express.json());

and

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

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