简体   繁体   English

使用Angular + Express发出POST请求时获取空响应正文

[英]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. 我正在尝试发出一个简单的POST请求,但从服务器返回的响应却是空的。 I've sifted through all the SO questions regarding this topic and tried the solutions posted but to no avail. 我已经筛选了有关该主题的所有SO问题,并尝试了发布的解决方案,但无济于事。

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 })); 我尝试更改请求标头选项以使用'application/x-www-form-urlencoded' ,并将我的快递应用中的app.use(bodyParser.urlencoded({ extended: true }));设置为app.use(bodyParser.urlencoded({ extended: true })); but that didn't work either. 但这也不起作用。

auth-service.service.ts 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) login.component.ts(调用登录服务方法)

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) server.js(我在这里定义了路由,但它们并不相关)

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: {} ) 但是,当我尝试使用Postman时,会得到期望的响应(即Request body: {}

I'm not sure as to why a response is retrieved when done through Postman but not when done through the app. 我不确定为什么通过Postman完成检索到的响应而不是通过应用程序完成时获得的响应。

Any help is appreciated. 任何帮助表示赞赏。 Thanks! 谢谢!

You need to set body for POST request in auth-service.service.ts : 您需要在auth-service.service.tsPOST请求设置body

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 尝试使用express.json丢失

app.use(express.json());

and

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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