如何抓住从AJAX传递给NodeJS的FormData? [英] How to grab FormData being passed from AJAX to NodeJS?

查看:712
本文介绍了如何抓住从AJAX传递给NodeJS的FormData?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不确定客户端或服务器上的代码是错误的吗?它工作,如果我不发送一个FormData(req.body读取信息),但一旦我改变它FormData,因为我想发送一个图片以及一些字符串,我在服务器端的标题上得到一个错误500。我的当前身体分析器的Req.body不会提取由AJAX JS请求发回的FormData ...

$ b

这是我的JS方面:

$ p $ var $ new $ {$ file $} (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,//不处理文件
contentType:false,//设置内容类型为false,因为jQuery会告诉服务器它的查询字符串请求$ b (b)b
$ b成功:函数(数据){
if(data){
alert(Product added);
successAddProject(data);
enableAddProjectButtons() ;
alert(data does not exist);
enableAddProjectButtons();
}
console.log(返回的数据是+ 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 (被调用的管理员身体是真实的);
var title;

title = req.body.title;

console.log(Called admin body is real+ title.length);


解决方案

docs for BodyParser - 对于多部分数据上传,你必须使用不同的模块,我选择了强大的。
https://github.com/expressjs/body-parser


  var form = new formidable.IncomingForm({ 
uploadDir:'_dirname',
keepExtensions:true
});

//解析文件上传
form.parse(req,function(err,fields,files){})


I am not sure where the code is wrong on the client or the server? It works if I do not send a FormData (req.body reads the info) but once I changed it to FormData since I am trying to send a picture along with some strings, I get a error 500 on the server side on the title.length console.log

Req.body with my current body-parser does not extract FormData being sent back by the AJAX JS Request...

This is my JS side:

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));
                    }
                });

This is the NodeJS side:

My app.js has these for body-parse:

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

Then the route is this:

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);

解决方案

according to the docs for BodyParser - for multi-part data uploads you have to use different modules, I chose formidable. https://github.com/expressjs/body-parser

var form = new formidable.IncomingForm({
          uploadDir: '_dirname',
          keepExtensions: true
        });

    // parse a file upload
    form.parse(req, function(err, fields, files) { })

这篇关于如何抓住从AJAX传递给NodeJS的FormData?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆