我不确定客户端或服务器上的代码错误在哪里?它可以工作,如果我不发送FormData(req.body读取信息),但一旦我将其更改为FormData,因为我试图发送图片和一些字符串,我在标题上的服务器端得到一个错误500。 length console.log
使用我当前的body-parser的Req.body不会提取由AJAX JS Request发回的FormData ...
这是我的JS方面:
var newProjectImage = $("#filebutton").get(0).files[0];
var formData = new FormData();
formData.append('picture', newProjectImage);
formData.append('title', newProjectTitle.trim());
$.ajax({
type: "POST",
url: "/adminAddProject",
data: formData,
cache: false,
dataType: 'json',
processData: false, // Don't process the files
contentType: false, // Set content type to false as jQuery will tell the server its a query string request
success: function (data) {
if(data) {
alert("Product added");
successAddProject(data);
enableAddProjectButtons();
} else {
alert("data does not exist ");
enableAddProjectButtons();
}
console.log("the data returned is " + JSON.stringify(data));
}
});
这是NodeJS方面:
我的app.js有这些用于正文解析:
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
然后路线是这样的:
router.post('/adminAddProject', function(req, res) {
console.log("Called admin add " + JSON.stringify(req.body));
if(req.cookies.token) {
console.log("Called admin token passes");
if(req.body) {
console.log("Called admin body is real ");
var title;
title = req.body.title;
console.log("Called admin body is real " + title.length);
答案 0 :(得分:0)
根据BodyParser的文档 - 对于多部分数据上传,你必须使用不同的模块,我选择了强大的。 https://github.com/expressjs/body-parser
context 'with keyword' do
let(:search_param) { "rizky" }
let(:doctor) { instance_double(Doctor) }
let(:results) { instance_double(Searchkick::Results) }
before do
allow(Doctor).to receive(:search).with(search_param) {:results}
end
it 'calls Doctor.search' do
get :search, search_param
expect(Doctor).to receive(:search).with(search_param)
end
end