为什么我的 req.body 是空的?平均堆栈 - NodeJs
Why is my req.body empty? MEAN Stack - NodeJs
我的数据从 front-end 到 back-end 的路径非常有效,直到我尝试发送 post 请求并访问 req.body。
表单数据正在正确发送,我可以看到它应该在开发人员工具的网络选项卡中,但是当我尝试访问它时,req.body object 是空的。请帮忙!!我敢肯定这是小事,但我在这里失眠了。
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader(
'Access-Control-Allow-Headers',
'Origin, X-Requested-With, Content-Type, Accept');
res.setHeader(
'Access-Control-Allow-Methods',
'GET, POST, PATCH, PUT, DELETE, OPTIONS'
);
next();
});
app.use('/api/manifests', manifestsRoutes);
router.post("", (req, res, next) => {
const manifest = new Manifest({
hazardId: req.body.hazardId,
serviceDate: req.body.serviceDate,
service: req.body.service,
gallonsRemoved: req.body.gallonsRemoved,
servicer: {
name: req.body.servicerName,
company: req.body.servicerCompany,
email: req.body.servicerEmail,
phone: req.body.servicerPhone
},
serviceFrequency: req.body.serviceFrequency,
disposalFacility: req.body.disposalFacility,
repairsMade: req.body.repairsMade
});
manifest.save().then(createdManifest => {
res.status(201).json({
message: 'Manifest created!',
manifest: {
...createdManifest,
id: createdManifest._id
}
});
})
.catch(error => {
res.status(500).json({
message: manifest,
error: error
});
});
});
addManifest(
hazardId: string,
serviceDate: Date,
service: string,
gallonsRemoved: string,
servicer: {
name: string,
company: string,
email: string,
phone: string
},
serviceFrequency: string,
disposalFacility: string,
repairsMade: string
) {
const datestr = (new Date(serviceDate)).toDateString();
const manifestData = new FormData();
manifestData.append('hazardId', hazardId);
manifestData.append('serviceDate', datestr);
manifestData.append('service', service);
manifestData.append('gallonsRemoved', gallonsRemoved);
manifestData.append('servicerName', servicer.name);
manifestData.append('servicerCompany', servicer.company);
manifestData.append('servicerEmail', servicer.email);
manifestData.append('servicerPhone', servicer.phone);
manifestData.append('serviceFrequency', serviceFrequency);
manifestData.append('disposalFacility', disposalFacility);
manifestData.append('repairsMade', repairsMade);
this.http
.post<{ message: string; manifest: Manifest }>(
'http://localhost:3000/api/manifests',
manifestData
)
.subscribe(responseData => {
console.log(responseData);
});
}
POST 调试器网络选项卡中的数据:
Request URL: http://localhost:3000/api/manifests
Request Method: POST
Status Code: 500 Internal Server Error
Remote Address: [::1]:3000
Referrer Policy: no-referrer-when-downgrade
响应Headers:
Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept
Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS
Access-Control-Allow-Origin: *
Connection: keep-alive
Content-Length: 2974
Content-Type: application/json; charset=utf-8
Date: Sat, 08 Feb 2020 06:29:58 GMT
ETag: W/"b9e-YODjimn7ORF5Sf5mzZD4Nwk6VPg"
X-Powered-By: Express
请求Headers:
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Connection: keep-alive
Content-Length: 1282
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryhOXfO3S3AyABWgsS
Host: localhost:3000
Origin: http://localhost:4200
Referer: http://localhost:4200/enter-manifest
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-site
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36
表单数据:
hazardId: 146852
serviceDate: Fri Feb 07 2020
service: Full pump and clean (all solids and liquids removed)
gallonsRemoved: 50
servicerName: test
servicerCompany: test
servicerEmail: test
servicerPhone: test
serviceFrequency: Quarterly
disposalFacility: test
repairsMade: null
将您的 addManifest
函数更改为:
addManifest(
hazardId: string,
serviceDate: Date,
service: string,
gallonsRemoved: string,
servicer: {
name: string,
company: string,
email: string,
phone: string
},
serviceFrequency: string,
disposalFacility: string,
repairsMade: string
) {
const datestr = (new Date(serviceDate)).toDateString();
var manifestData = {
'hazardId': hazardId,
'serviceDate': datestr,
'gallonsRemoved': gallonsRemoved,
'servicerName': servicer.name,
'servicerCompany': servicer.company,
'servicerEmail': servicer.email,
'servicerPhone': servicer.phone,
'serviceFrequency': serviceFrequency,
'disposalFacility': disposalFacility,
'repairsMade': repairsMade
};
const httpOptions = {headers: new HttpHeaders({'Content-Type': 'application/json'})};
this.http
.post<{ message: string; manifest: Manifest }>(
'http://localhost:3000/api/manifests',
manifestData,
httpOptions
)
.subscribe(responseData => {
console.log(responseData);
});
}
将 FormData
更改为 JavaScriptObject
并为请求 header
添加了 JSON Content-Type
这行得通吗?
我的数据从 front-end 到 back-end 的路径非常有效,直到我尝试发送 post 请求并访问 req.body。
表单数据正在正确发送,我可以看到它应该在开发人员工具的网络选项卡中,但是当我尝试访问它时,req.body object 是空的。请帮忙!!我敢肯定这是小事,但我在这里失眠了。
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader(
'Access-Control-Allow-Headers',
'Origin, X-Requested-With, Content-Type, Accept');
res.setHeader(
'Access-Control-Allow-Methods',
'GET, POST, PATCH, PUT, DELETE, OPTIONS'
);
next();
});
app.use('/api/manifests', manifestsRoutes);
router.post("", (req, res, next) => {
const manifest = new Manifest({
hazardId: req.body.hazardId,
serviceDate: req.body.serviceDate,
service: req.body.service,
gallonsRemoved: req.body.gallonsRemoved,
servicer: {
name: req.body.servicerName,
company: req.body.servicerCompany,
email: req.body.servicerEmail,
phone: req.body.servicerPhone
},
serviceFrequency: req.body.serviceFrequency,
disposalFacility: req.body.disposalFacility,
repairsMade: req.body.repairsMade
});
manifest.save().then(createdManifest => {
res.status(201).json({
message: 'Manifest created!',
manifest: {
...createdManifest,
id: createdManifest._id
}
});
})
.catch(error => {
res.status(500).json({
message: manifest,
error: error
});
});
});
addManifest(
hazardId: string,
serviceDate: Date,
service: string,
gallonsRemoved: string,
servicer: {
name: string,
company: string,
email: string,
phone: string
},
serviceFrequency: string,
disposalFacility: string,
repairsMade: string
) {
const datestr = (new Date(serviceDate)).toDateString();
const manifestData = new FormData();
manifestData.append('hazardId', hazardId);
manifestData.append('serviceDate', datestr);
manifestData.append('service', service);
manifestData.append('gallonsRemoved', gallonsRemoved);
manifestData.append('servicerName', servicer.name);
manifestData.append('servicerCompany', servicer.company);
manifestData.append('servicerEmail', servicer.email);
manifestData.append('servicerPhone', servicer.phone);
manifestData.append('serviceFrequency', serviceFrequency);
manifestData.append('disposalFacility', disposalFacility);
manifestData.append('repairsMade', repairsMade);
this.http
.post<{ message: string; manifest: Manifest }>(
'http://localhost:3000/api/manifests',
manifestData
)
.subscribe(responseData => {
console.log(responseData);
});
}
POST 调试器网络选项卡中的数据:
Request URL: http://localhost:3000/api/manifests
Request Method: POST
Status Code: 500 Internal Server Error
Remote Address: [::1]:3000
Referrer Policy: no-referrer-when-downgrade
响应Headers:
Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept
Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS
Access-Control-Allow-Origin: *
Connection: keep-alive
Content-Length: 2974
Content-Type: application/json; charset=utf-8
Date: Sat, 08 Feb 2020 06:29:58 GMT
ETag: W/"b9e-YODjimn7ORF5Sf5mzZD4Nwk6VPg"
X-Powered-By: Express
请求Headers:
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Connection: keep-alive
Content-Length: 1282
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryhOXfO3S3AyABWgsS
Host: localhost:3000
Origin: http://localhost:4200
Referer: http://localhost:4200/enter-manifest
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-site
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36
表单数据:
hazardId: 146852
serviceDate: Fri Feb 07 2020
service: Full pump and clean (all solids and liquids removed)
gallonsRemoved: 50
servicerName: test
servicerCompany: test
servicerEmail: test
servicerPhone: test
serviceFrequency: Quarterly
disposalFacility: test
repairsMade: null
将您的 addManifest
函数更改为:
addManifest(
hazardId: string,
serviceDate: Date,
service: string,
gallonsRemoved: string,
servicer: {
name: string,
company: string,
email: string,
phone: string
},
serviceFrequency: string,
disposalFacility: string,
repairsMade: string
) {
const datestr = (new Date(serviceDate)).toDateString();
var manifestData = {
'hazardId': hazardId,
'serviceDate': datestr,
'gallonsRemoved': gallonsRemoved,
'servicerName': servicer.name,
'servicerCompany': servicer.company,
'servicerEmail': servicer.email,
'servicerPhone': servicer.phone,
'serviceFrequency': serviceFrequency,
'disposalFacility': disposalFacility,
'repairsMade': repairsMade
};
const httpOptions = {headers: new HttpHeaders({'Content-Type': 'application/json'})};
this.http
.post<{ message: string; manifest: Manifest }>(
'http://localhost:3000/api/manifests',
manifestData,
httpOptions
)
.subscribe(responseData => {
console.log(responseData);
});
}
将 FormData
更改为 JavaScriptObject
并为请求 header
JSON Content-Type
这行得通吗?