我正在尝试使用 ajax 请求将一些数据传递到我的 node.js 服务器。
不幸的是,我的服务器记录了一个空对象,并且我的 ajax 调用没有记录任何成功或错误。
这是我的代码片段:
var fd = new FormData();
function appendPicture(){
fd.append('picture_data', that.state.newFeedMediaData);
fd.append('content', that.state.newFeedContent);
fd.append('img_inline_style', img_inline);
}
var p1 = Promise.resolve(appendPicture());
p1.then(function(v){
console.log(fd);
$.ajax({
url: '/api/setNewFeedPost',
data: fd,
processData: false,
contentType: false,
enctype: 'multipart/form-data',
type: 'POST',
success: function(data){
console.log("success");
},
error: function(data){
console.log("error");
}
});
});
img_inline_style 包含以下对象:
{Filter: "grayscale(0%) brightness(100%) contrast(100%) sepia(0%)"
WebkitFilter: "grayscale(0%) brightness(100%) contrast(100%) sepia(0%)"
backgroundImage: ""
backgroundPositionY: -66
backgroundSize: "cover"
height: "100%"}
即使我的 sendObj 内部出现问题,我也不认为这就是问题,因为即使我尝试发送一些简单的字符串,例如 "test"
,请求也不会发生。
为什么会这样?
其他信息:
在我的node.js服务器端,我只是记录接收到的数据,这些数据就像一个空对象一样打印出来
Received data: {}
我正在使用带有express的node.js,并且我的api文件中的ajax帖子的服务器端渲染脚本如下所示:
router.post('/setNewFeedPost', function(req, response, next){
console.log("Set new Feedpost content: ",req.body);
});
最佳答案
在这里进行大胆的猜测,但您可能会缺少处理多部分请求的正确中间件。可悲的是, express 可能相当令人畏惧,而这就是其中之一。
如 How to get POST a query in Express.js/Node.js? 所示,需要添加各种中间件来支持各种类型的请求体。正如已经指出的那样,您需要 body-parser用于解析请求体。但是,由于您使用的是 multipart
,因此不能简单地依赖 body-parser。以下是他们当前的自述文件
的摘录:
Node.js body parsing middleware.
This does not handle multipart bodies, due to their complex and typically large nature.
它继续列出了各种替代方案。其中之一是 express 自己的multer 。他们的 README
非常好,但是为了完整起见,我决定整理一个小示例来稍微反射(reflect)您的用例:
app.js
var console = require("console");
var path = require('path');
var multer = require('multer');
var express = require('express');
var app = express();
// using path with __dirname is essential so you avoid the common pitfall of using
// relative paths, where you can never be sure if they are calculated
// from the current working directory or the directory of the file.
var upload = multer({dest: path.join(__dirname, 'uploads')});
// upload.any() is merely used for demonstration purposes and
// I do not recommend using this in production! See their README.
app.post('/save', upload.any(), function(req, res) {
console.log('Files', req.files); // All files are in here.
console.log('Body Data', req.body); // The rest of the data here.
// It is important to answer your client with something.
// Otherwise the client will never know you've received anything
// (resulting in a "pending" state and timeout errors).
res.send('win');
});
index.html
<form action="#">
<input type="file" name="foo_img">
<button type="submit">Lets go</button>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script>
var img_inline_style = {
backgroundImage: "",
backgroundPositionY: -66,
height: "100%"
};
$('form').submit(function(event) {
event.preventDefault();
// This is basically what you are doing, I guess.
var data = new FormData();
data.append('picture_data', $('input').get(0).files[0]);
data.append('content', 'foobarbarz');
// As correctly pointed out by Quentin's answer, you can't simply
// send objects. You need to transform them into a string. Here
// I'm doing this by converting the object into a string via JSON.
data.append('img_inline_style', JSON.stringify(img_inline_style));
$.ajax({
url: '/save',
data: data,
processData: false,
contentType: false,
enctype: 'multipart/form-data',
type: 'POST',
success: function(data){
console.log("success");
},
error: function(data){
console.log("error");
}
});
});
</script>
结果
运行此程序时,可以在服务器上观察到以下输出:
Files [ { fieldname: 'picture_data',
originalname: 'IMG_6365.JPG',
encoding: '7bit',
mimetype: 'image/jpeg',
destination: '/Users/luis/Desktop/test/uploads',
filename: '743c2599a93761a347ce0951ec746927',
path: '/Users/luis/Desktop/test/uploads/743c2599a93761a347ce0951ec746927',
size: 1561538 } ]
Body Data { content: 'foobarbarz',
img_inline_style: '{"backgroundImage":"","backgroundPositionY":-66,"height":"100%"}' }
正如您所看到的,我选择的文件和其余数据都在那里。成功!
希望这有帮助:)
关于javascript - Ajax请求根本没有被触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34558231/