首页 > 解决方案 > nodejs中的错误消息:后端返回代码400,正文为空

问题描述

我正在使用带有 Angular 6 的 MEAN Stack 开发一个 Web 应用程序。我已经为以下错误苦苦挣扎了好几天。我有一个显示颜色选择器的输入字段。它允许我们选择颜色。这是我的颜色模式。

var mongoose = require('mongoose');

var rdaColorSchema = new mongoose.Schema({  
  colorMovementBox: {
      type : String,
  },
});
module.exports = mongoose.model('rdaColor', rdaColorSchema);

这是我的后端。

router.post('/save', (req, res)=>{
    var rdaColorVal = new rdaColor(
        {
            colorMovementBox: req.body.colorMovementBox,
        }
    );

rdaColorVal.save((err,doc)=> {
    if(!err){

        res.send(doc);}
        else{
            console.log(err);
        }
        });
});

这是我的服务文件。

export class RdaColorService {

  constructor(private http: HttpClient) { }

     private handleError(error: HttpErrorResponse) {
        if (error.error instanceof ErrorEvent) {
            // A client-side or network error occurred. Handle it accordingly.
            console.error('An error occurred:', error.error.message);
        } else {
            // The backend returned an unsuccessful response code.
            // The response body may contain clues as to what went wrong,
            console.error(
                `Backend returned code ${error.status}, ` +
                `body was: ${error.error}`);
        }
        // return an observable with a user-facing error message
        return throwError('Something bad happened; please try again later.');
    };
        private extractData(res: Response) {
        let body = res;
        return body || [];
    }
    saveRdaColor(rdaColor): Observable<any> {
        return this.http.post('/rdaColor/save', rdaColor, httpOptions)
            .pipe(
                catchError(this.handleError)
            );
    }

}

当我调试项目时,我可以在前端看到颜色值(我使用 ngx-color 选择器来选择颜色)。但是后端给出了以下错误。 错误

我搜索了很多关于这个错误的信息。但没有任何效果。

标签: node.jsweberror-handlingangular6mean-stack

解决方案


请求正文是null.

你需要:

{ colorMovementBox: "<value here>" }从 Angular 6 POST 调用发送请求正文:

this.httpClient.post("/rdaColor/save", { "colorMovementBox": "<value here>" })
    .subscribe(
          data => {
              console.log("POST Request is successful ", data);
          },
          error => {
              console.log("Error:", error);
          }
    );

通过以下方式将body-parser中间件合并到您的快速后端npm i -S body-parser

const app = express();
var bodyParser = require('body-parser')
.
.
.
app.use(bodyParser.json());

推荐阅读