javascript - Ajax请求根本没有被触发

标签 javascript jquery ajax

我正在尝试使用 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/

相关文章:

javascript - 使用 Ajax 延长 PHP session 超时

JavaScript 通过名称获取元素

javascript - 使用 iMacros 向下滚动到页面底部

javascript - Cube.js - 无法连接 2 个或更多表,但不断收到 "Can' t find join path to join“错误

jquery - ScrollMagic 固定并显示问题

javascript - jQuery 自定义插件 : returning a value to event

php - 从外部 PHP 文件填充 HTML 文本框

javascript - 从 JavaScript angular js 中的 URL 成功获取数据(Ajax)

javascript - 使用 javascript/jQuery 对选择列表中的选项进行排序...但不是按字母顺序排序

Javascript动态加载html到另一个html文件中