Node.js nodejs中的错误消息:后端返回代码400,正文为空
我正在使用MEAN Stack和Angular 6开发一个web应用程序。我为以下错误挣扎了好几天。 我有一个显示颜色选择器的输入字段。它允许我们选择颜色。 这是我的颜色模式Node.js nodejs中的错误消息:后端返回代码400,正文为空,node.js,web,error-handling,angular6,mean-stack,Node.js,Web,Error Handling,Angular6,Mean Stack,我正在使用MEAN Stack和Angular 6开发一个web应用程序。我为以下错误挣扎了好几天。 我有一个显示颜色选择器的输入字段。它允许我们选择颜色。 这是我的颜色模式 var mongoose = require('mongoose'); var rdaColorSchema = new mongoose.Schema({ colorMovementBox: { type : String, }, }); module.exports = mongoose.mo
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)
);
}
}
导出类RdaColorService{
构造函数(私有http:HttpClient){}
私有句柄错误(错误:HttpErrorResponse){
if(error.error instanceof ErrorEvent){
//发生客户端或网络错误。请相应地进行处理。
console.error('发生错误:',error.error.message);
}否则{
//后端返回了一个不成功的响应代码。
//回应主体可能包含了错误的线索,
控制台错误(
`后端返回代码${error.status},`+
`正文是:${error.error}`);
}
//返回带有面向用户的错误消息的可观察对象
return-throwerr('发生了不好的事情,请稍后再试');
};
私有数据(res:Response){
让body=res;
返回体| |[];
}
saveRdaColor(rdaColor):可观察
我搜索了很多关于这个错误的信息。但是没有任何结果。请求正文为null
您需要:
从Angular 6 POST调用发送请求正文{colorMovementBox:}
:
this.httpClient.post("/rdaColor/save", { "colorMovementBox": "<value here>" })
.subscribe(
data => {
console.log("POST Request is successful ", data);
},
error => {
console.log("Error:", error);
}
);
能否在服务器端共享更多代码?是否将bodyParser用作中间件?您需要发送请求正文{colorMovementBox:“”
并合并主体解析器中间件。@MattKuhns是的,我使用的是主体解析器。我也已将服务文件添加到问题中。@AdiSivasankaran感谢您的建议。我们是否应在服务中发送请求主体?
const app = express();
var bodyParser = require('body-parser')
.
.
.
app.use(bodyParser.json());