如何将数据从JQuery AJAX请求发送到Node.js服务器 [英] How to send data from JQuery AJAX request to Node.js server

查看:175
本文介绍了如何将数据从JQuery AJAX请求发送到Node.js服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做什么:
只需使用jquery ajax请求将一些数据(例如json)发送到node.js http服务器.

What i want to do:
Simply send some data (json for example), to a node.js http server, using jquery ajax requests.

由于某种原因,我无法在服务器上获取数据,因为它从不触发请求的数据"事件.

For some reason, i can't manage to get the data on the server, cause it never fires the 'data' event of the request.

客户代码:

$.ajax({
    url: server,
    dataType: "jsonp",
    data: '{"data": "TEST"}',
    jsonpCallback: 'callback',
    success: function (data) {
        var ret = jQuery.parseJSON(data);
        $('#lblResponse').html(ret.msg);
    },
    error: function (xhr, status, error) {
        console.log('Error: ' + error.message);
        $('#lblResponse').html('Error connecting to the server.');
    }
});

服务器代码:

var http = require('http');
http.createServer(function (req, res) {

    console.log('Request received');

    res.writeHead(200, { 'Content-Type': 'text/plain' });
    req.on('data', function (chunk) {
        console.log('GOT DATA!');
    });
    res.end('callback(\'{\"msg\": \"OK\"}\')');

}).listen(8080, '192.168.0.143');
console.log('Server running at http://192.168.0.143:8080/');

正如我所说,它永远不会进入请求的数据"事件.

As i said, it never gets into the 'data' event of the request.

评论:
1.记录收到请求"消息;
2.响应很好,无法使用数据将其返回给客户端;

Comments:
1. It logs the 'Request received' message;
2. The response is fine, im able to handle it back on the client, with data;

有帮助吗?我想念什么吗?

Any help? Am i missing something?

谢谢大家.


根据答案注释了代码的最终版本:


Commented final version of the code, based on the answer:

客户代码:

$.ajax({
type: 'POST' // added,
url: server,
data: '{"data": "TEST"}',
//dataType: 'jsonp' - removed
//jsonpCallback: 'callback' - removed
success: function (data) {
    var ret = jQuery.parseJSON(data);
    $('#lblResponse').html(ret.msg);
},
error: function (xhr, status, error) {
    console.log('Error: ' + error.message);
    $('#lblResponse').html('Error connecting to the server.');
}
});


服务器代码:


Server code:

var http = require('http');
http.createServer(function (req, res) {

    console.log('Request received');

    res.writeHead(200, { 
        'Content-Type': 'text/plain',
        'Access-Control-Allow-Origin': '*' // implementation of CORS
    });
    req.on('data', function (chunk) {
        console.log('GOT DATA!');
    });

    res.end('{"msg": "OK"}'); // removed the 'callback' stuff

}).listen(8080, '192.168.0.143');
console.log('Server running at http://192.168.0.143:8080/');


由于我想允许跨域请求,因此我添加了 CORS 的实现.


Since i want to allow Cross-Domain requests, i added an implementation of CORS.

谢谢!

推荐答案

要使'data'事件在node.js服务器端触发,您必须对数据进行POST.也就是说,数据"事件仅响应POST数据.将"jsonp"指定为数据格式会强制执行GET请求,因为jsonp在jquery文档中定义为:

To get the 'data' event to fire on the node.js server side, you have to POST the data. That is, the 'data' event only responds to POSTed data. Specifying 'jsonp' as the data format forces a GET request, since jsonp is defined in the jquery documentation as:

"jsonp":使用JSONP加载JSON块.添加一个额外的?callback =?" URL的末尾以指定回调

"jsonp": Loads in a JSON block using JSONP. Adds an extra "?callback=?" to the end of your URL to specify the callback

这是修改客户端以触发数据事件的方式.

Here is how you modify the client to get your data event to fire.

<html>
<head>
    <script language="javascript" type="text/javascript" src="jquery-1.8.3.min.js"></script>
</head>

<body>
    response here: <p id="lblResponse">fill me in</p>

<script type="text/javascript">
$(document).ready(function() {
    $.ajax({
        url: 'http://192.168.0.143:8080',
        // dataType: "jsonp",
        data: '{"data": "TEST"}',
        type: 'POST',
        jsonpCallback: 'callback', // this is not relevant to the POST anymore
        success: function (data) {
            var ret = jQuery.parseJSON(data);
            $('#lblResponse').html(ret.msg);
            console.log('Success: ')
        },
        error: function (xhr, status, error) {
            console.log('Error: ' + error.message);
            $('#lblResponse').html('Error connecting to the server.');
        },
    });
});
</script>

</body>
</html>

一些有用的行可以帮助您调试服务器端:

Some helpful lines to help you debug the server side:

var http = require('http');
var util = require('util')
http.createServer(function (req, res) {

    console.log('Request received: ');
    util.log(util.inspect(req)) // this line helps you inspect the request so you can see whether the data is in the url (GET) or the req body (POST)
    util.log('Request recieved: \nmethod: ' + req.method + '\nurl: ' + req.url) // this line logs just the method and url

    res.writeHead(200, { 'Content-Type': 'text/plain' });
    req.on('data', function (chunk) {
        console.log('GOT DATA!');
    });
    res.end('callback(\'{\"msg\": \"OK\"}\')');

}).listen(8080);
console.log('Server running on port 8080');

节点上数据事件的目的是建立主体-它对单个http请求触发多次,对于它收到的每个数据块都触发一次.这是node.js的异步特性-服务器在接收数据块之间执行其他工作.

The purpose of the data event on the node side is to build up the body - it fires multiple times per a single http request, once for each chunk of data that it receives. This is the asynchronous nature of node.js - the server does other work in between receiving chunks of data.

这篇关于如何将数据从JQuery AJAX请求发送到Node.js服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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