简体   繁体   English

使用$ .ajax发布将数据发送到node.js服务器

[英]Using $.ajax post to send data to node.js server

First of all my questions might get you relate to others but I have got many solutions but they did not work. 首先,我的问题可能会让您与他人建立联系,但是我有很多解决方案,但是它们没有用。 So I am posting my problem hope you guys can help me.! 所以我发布了我的问题,希望你们能帮助我。

I have created two file posts.ejs and app.js(routes implemented in this file). 我创建了两个文件posts.ejs和app.js(在此文件中实现的路由)。

Post.ejs Post.ejs

Ajax call:- Ajax电话:-

 function SaveLocalNews(postData, cb) {

        var headerSetting = {
            "api-key": 1,
            "UDID": getUDID(),
            "device-type": getDeviceType(),
            "Authorization": "Authorization"
        };
        var requestMedia = $.ajax({
            url: "/posts",
            type: "POST",
            data: postData,
            dataType: "json",
            cache: false,
            processData: false,
            contentType: false,
            headers: headerSetting
        });

        requestMedia.done(function (data) {
            if (data.status) {
                alert_message("success");
            } else {
                alert_message("fail" + "success");
                // TODO: Handle not uploaded media
            }
            return;
        });
        requestMedia.fail(function (jqXHR, textStatus) {
            // TODO: Handle not uploaded media
            alert_message("fail");
            return
        });

} }

App.js App.js

var express = require("express"),
app = express(),
bodyParser = require("body-parser"),
mysql = require("mysql");

var session = require('express-session');

app.set("view engine", "ejs");
app.use(bodyParser.urlencoded({extended: true}));

app.use(express.static(__dirname + '/public'));

app.post("/posts",  function (req, res) {
//I am not getting body/data what I have passed in ajax request. 
    console.log(req.body); // Output:-  {}
});

I hope you clear with my problem. 希望您能解决我的问题。

It seems that you need to make at least few changes: 似乎您至少需要进行一些更改:

On the server side 在服务器端

add app.use( bodyParser.json()); 添加app.use( bodyParser.json());


On the client side 在客户端

Update your ajax to: 将您的ajax更新为:

  var requestMedia = $.ajax({
        url: "/posts",
        type: "POST",
        data: JSON.stringify(postData),
        dataType: "json",
        cache: false, 
        contentType: "application/json",
        headers: headerSetting
    });

Reasons for these changes 这些变化的原因

I would change the ajax to data: JSON.stringify(postData), instead of using processData: false, . 我将ajax更改为data: JSON.stringify(postData),而不是使用processData: false, data: JSON.stringify(postData), I think the two are basically equivalent, I just prefer this way personally. 我认为两者基本上是相同的,我个人更喜欢这种方式。

From the docs 来自文档

data 数据

Type: PlainObject or String or Array 类型:PlainObject或字符串或数组

Data to be sent to the server. 数据要发送到服务器。 It is converted to a query string, if not already a string . 如果尚未 转换为查询字符串, 则将 其转换为查询 字符串 It's appended to the url for GET-requests. 它被附加到GET请求的URL上。 See processData option to prevent this automatic processing. 请参阅processData选项以防止这种自动处理。 Object must be Key/Value pairs. 对象必须是键/值对。 If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below). 如果value是一个Array,则jQuery会根据传统设置(如下所述)的值,使用相同的键序列化多个值。


change your ajax to contentType: 'application/json', since false will cause it to set no content type header and might be causing node to not see the post body correctly. 将您的ajax更改为contentType: 'application/json',因为false会导致它不设置内容类型标头,并且可能导致节点无法正确看到帖子主体。

From the docs 来自文档

contentType (default: 'application/x-www-form-urlencoded; charset=UTF-8') contentType(预设值:'application / x-www-form-urlencoded; charset = UTF-8')

Type: Boolean or String 类型:布尔值或字符串

When sending data to the server, use this content type. 将数据发送到服务器时,请使用此内容类型。 Default is "application/x-www-form-urlencoded; charset=UTF-8", which is fine for most cases. 默认值为“ application / x-www-form-urlencoded; charset = UTF-8”,在大多数情况下都可以。 If you explicitly pass in a content-type to $.ajax(), then it is always sent to the server (even if no data is sent). 如果您将内容类型显式传递给$ .ajax(),则该内容类型将始终发送到服务器(即使未发送任何数据)。 As of jQuery 1.6 you can pass false to tell jQuery to not set any content type header. 从jQuery 1.6开始,您可以传递false来告诉jQuery不要设置任何内容类型标头。


You also want to change dataType: false, to dataType: 'json', since your done handler is looking for data.status which means you are in fact expecting json to be returned (even though your server side code doesnt seem to do that yet) 您还想将dataType: false,更改为dataType: 'json',因为您完成的处理程序正在寻找data.status ,这意味着您实际上希望返回json(即使您的服务器端代码似乎还没有这样做) )

From the docs 来自文档

dataType (default: Intelligent Guess (xml, json, script, or html)) dataType(默认值:Intelligent Guess(xml,json,脚本或html))

Type: String 类型:字符串

The type of data that you're expecting back from the server. 您期望从服务器返回的数据类型。 If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string). 如果未指定,则jQuery将尝试根据响应的MIME类型来推断它(XML MIME类型将产生XML,在1.4中,JSON将产生JavaScript对象,在1.4中,脚本将执行该脚本,而其他所有内容将是以字符串形式返回)。


If you updated to use JSON.stringify(postData) , remove the processData: false, . 如果更新为使用JSON.stringify(postData) ,则删除processData: false, JSON.stringify(postData)

From the docs 来自文档

processData (default: true) processData(默认值:true)

Type: Boolean 类型:布尔

By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". 默认情况下,作为对象传递给data选项的数据(从技术上讲,不是字符串)将被处理并转换为查询字符串,以适合默认的内容类型“ application / x-www-form-urlencoded” 。 If you want to send a DOMDocument, or other non-processed data, set this option to false. 如果要发送DOMDocument或其他未处理的数据,请将此选项设置为false。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM