node.js - 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 选择器来选择颜色)。但是后端给出了以下错误。
我搜索了很多关于这个错误的信息。但没有任何效果。
解决方案
请求正文是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());
推荐阅读
- java - 我的 Webview 应用程序在进行信使聊天时不断崩溃
- visual-studio-code - 如何仅使用键盘在终端中复制一行文本?
- c++ - CMake 将目录路径解释为 LIBRARY_OUTPUT_DIRECTORY 中的绝对路径与 RUNTIME_OUTPUT_DIRECTORY 中的相对路径
- java - 如何仅使用 if 语句检查范围
- java - android studio 通过 USB 与 arduino 进行串行通信
- c - 字符串连接在 C 中不起作用 (TDM-GCC-64)
- c - 将值设置为结构指针
- javascript - 文本基线的 Illustrator 脚本 (javascript)
- hyperledger-fabric - 错误:在结构 1.2 中找不到模块“结构客户端”
- javascript - 我们可以对 mocha 中的测试错误进行排序吗?