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

时间:2022-10-22 22:57:46

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.

我希望你清楚我的问题。

1 个解决方案

#1


0  

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,. I think the two are basically equivalent, I just prefer this way personally.

我会将ajax更改为data:JSON.stringify(postData),而不是使用processData:false。我认为这两者基本相同,我个人更喜欢这种方式。

From the docs

来自文档

data

数据

Type: PlainObject or String or Array

键入:PlainObject或String或Array

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. See processData option to prevent this automatic processing. 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).

要发送到服务器的数据。如果不是字符串,它将转换为查询字符串。它附加到GET请求的URL。请参阅processData选项以防止此自动处理。对象必须是键/值对。如果value是一个数组,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. If you explicitly pass in a content-type to $.ajax(), then it is always sent to the server (even if no data is sent). As of jQuery 1.6 you can pass false to tell jQuery to not set any content type header.

将数据发送到服务器时,请使用此内容类型。默认为“application / x-www-form-urlencoded; charset = UTF-8”,这在大多数情况下都适用。如果您明确地将内容类型传递给$ .ajax(),那么它总是被发送到服务器(即使没有数据发送)。从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',因为您的done处理程序正在查找data.status,这意味着您实际上希望返回json(即使您的服务器端代码似乎还没有这样做) )

From the docs

来自文档

dataType (default: Intelligent Guess (xml, json, script, or html))

dataType(默认值:Intelligent Guess(xml,json,script或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。

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". If you want to send a DOMDocument, or other non-processed data, set this option to false.

默认情况下,作为对象传入数据选项的数据(技术上,不是字符串)将被处理并转换为查询字符串,适合默认内容类型“application / x-www-form-urlencoded” 。如果要发送DOMDocument或其他未处理的数据,请将此选项设置为false。

#1


0  

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,. I think the two are basically equivalent, I just prefer this way personally.

我会将ajax更改为data:JSON.stringify(postData),而不是使用processData:false。我认为这两者基本相同,我个人更喜欢这种方式。

From the docs

来自文档

data

数据

Type: PlainObject or String or Array

键入:PlainObject或String或Array

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. See processData option to prevent this automatic processing. 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).

要发送到服务器的数据。如果不是字符串,它将转换为查询字符串。它附加到GET请求的URL。请参阅processData选项以防止此自动处理。对象必须是键/值对。如果value是一个数组,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. If you explicitly pass in a content-type to $.ajax(), then it is always sent to the server (even if no data is sent). As of jQuery 1.6 you can pass false to tell jQuery to not set any content type header.

将数据发送到服务器时,请使用此内容类型。默认为“application / x-www-form-urlencoded; charset = UTF-8”,这在大多数情况下都适用。如果您明确地将内容类型传递给$ .ajax(),那么它总是被发送到服务器(即使没有数据发送)。从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',因为您的done处理程序正在查找data.status,这意味着您实际上希望返回json(即使您的服务器端代码似乎还没有这样做) )

From the docs

来自文档

dataType (default: Intelligent Guess (xml, json, script, or html))

dataType(默认值:Intelligent Guess(xml,json,script或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。

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". If you want to send a DOMDocument, or other non-processed data, set this option to false.

默认情况下,作为对象传入数据选项的数据(技术上,不是字符串)将被处理并转换为查询字符串,适合默认内容类型“application / x-www-form-urlencoded” 。如果要发送DOMDocument或其他未处理的数据,请将此选项设置为false。