如何将数据从客户端的 html 发送到 node.js 服务器? [英] How to send data from client's html to node.js server?

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

问题描述

我想将 JSON 数据发送到 node.js 服务器.

I wanted to send JSON data to node.js server.

这是我的 server.js :

This is my server.js :

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','Access-Control-Allow-Origin': '*' });
req.on('data', function (chunk) {
    console.log('GOT DATA!');
});
res.end('callback(\'{\"msg\": \"OK\"}\')');

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

这是一个 html 文件:

This is html file :

<!doctype html>
<html>
<head>

<script src="http://code.jquery.com/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://127.0.0.1:8090/',
    // dataType: "jsonp",
    data:   '{ "name":"John", "age":30, "car":null },
    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>

但我收到此错误:

"VM162:1 Uncaught SyntaxError: Unexpected token c in JSON at position 0
at JSON.parse (<anonymous>)
at Function.parseJSON (jquery-1.8.3.js:514)
at Object.success (file:///home/techm/Desktop/test%20(server-client)/client.html:20:30)
at fire (jquery-1.8.3.js:974)
at Object.fireWith [as resolveWith] (jquery-1.8.3.js:1084)
at done (jquery-1.8.3.js:7803)
at XMLHttpRequest.callback (jquery-1.8.3.js:8518)

我不知道为什么会收到此错误,因为我对 node.js 服务器并不陌生.如果我得到数据,我想将其保存在本地文件中.

I don't why I am getting this error because I am little new to node.js server. And if I get the data I want to save it in a local file.

推荐答案

你的ajax请求应该是这样的

Your ajax request should be like this

$.ajax({
    url: 'http://127.0.0.1:8090/',
    data: { "name": "John", "age":30, "car":null },
    type: 'POST'
    .....
})

并在 server.js 的 createServer 方法中更新这个

And in createServer method of server.js update this

if (req.method == 'POST') {
    console.log("POST");
    var body = '';
    req.on('data', function (data) {
        body += data;
        console.log("Partial body: " + body);
    });
    req.on('end', function () {
        console.log("Body: " + body);
    });
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end('callback(\'{\"msg\": \"OK\"}\')');
}
else
{
    console.log("GET");
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end('callback(\'{\"msg\": \"OK\"}\')');
}

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

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