最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Node.js, Ajax sending and receiving Json - Stack Overflow

programmeradmin10浏览0评论

Using Ajax, I'm trying to just send Json data to a node server no processing involved just alerting when it's sent and alerting when it's received:

This is my html5: Simple button with an onclick function to trigger the function to use the ajax call

<!DOCTYPE HTML>
<html>
    <head>
        <script>
            function send()
            {
                //alert("Hello World");
                $.ajax
                ({
                    type: "post",
                    url: "http://localhost:8000", 
                    dataType: "json",
                    contentType: "application/json; charset=UTF-8",
                    data:  JSON.stringify({name: "Dennis", address: {city: "Dub", country: "IE"}})
                }).done(function ( data ) {alert("ajax callback response:" + data);
            });
        </script>
    </head>
    <body>
        <button onclick="send()">Click Me!</button>
    </body>
</html>

This is a portion of my node server: For creating a server and listening for certain actions

var port = 8000;
var server = http.createServer();
server.on('request', request);
server.listen(port);

function request(request, response) 
{
    var store = '';
    response.writeHead(200, {"Content-Type": "text/json"});
    request.on('data', function(data) 
    {
        store += data;
    });
    request.on('end', function() 
    {
       store = JSON.parse(store);
        console.log(store); 
        response.end(store);
    });
}  

No alerts are being fired so I don't think the ajax is attempting to send the information.

Using Ajax, I'm trying to just send Json data to a node server no processing involved just alerting when it's sent and alerting when it's received:

This is my html5: Simple button with an onclick function to trigger the function to use the ajax call

<!DOCTYPE HTML>
<html>
    <head>
        <script>
            function send()
            {
                //alert("Hello World");
                $.ajax
                ({
                    type: "post",
                    url: "http://localhost:8000", 
                    dataType: "json",
                    contentType: "application/json; charset=UTF-8",
                    data:  JSON.stringify({name: "Dennis", address: {city: "Dub", country: "IE"}})
                }).done(function ( data ) {alert("ajax callback response:" + data);
            });
        </script>
    </head>
    <body>
        <button onclick="send()">Click Me!</button>
    </body>
</html>

This is a portion of my node server: For creating a server and listening for certain actions

var port = 8000;
var server = http.createServer();
server.on('request', request);
server.listen(port);

function request(request, response) 
{
    var store = '';
    response.writeHead(200, {"Content-Type": "text/json"});
    request.on('data', function(data) 
    {
        store += data;
    });
    request.on('end', function() 
    {
       store = JSON.parse(store);
        console.log(store); 
        response.end(store);
    });
}  

No alerts are being fired so I don't think the ajax is attempting to send the information.

Share Improve this question edited Apr 25, 2017 at 17:23 Cœur 38.7k26 gold badges203 silver badges277 bronze badges asked May 21, 2014 at 13:26 Dennington-bearDennington-bear 1,7825 gold badges20 silver badges45 bronze badges 5
  • 1 Open your console, do you see any errors? – tymeJV Commented May 21, 2014 at 13:28
  • 2 Open your developer tools Net tab, do you see the request you expect and the response you expect? – Quentin Commented May 21, 2014 at 13:28
  • 1 Why are you telling jQuery to expect JSON when you have a text/plain content type? Why are you sending a 200 response with no response body? – Quentin Commented May 21, 2014 at 13:30
  • @Quentin ok i understand I was doing that wrong! now its stating that my send is unreferenced – Dennington-bear Commented May 21, 2014 at 14:48
  • Paste your JS into jshint. (but I'd have expected that error to show up in the JS console when the document loaded). – Quentin Commented May 21, 2014 at 14:51
Add a ment  | 

2 Answers 2

Reset to default 7

try this on the server side:

var port = 8000;
var http = require("http");
var server = http.createServer();
server.on('request', request);
server.listen(port);
function request(request, response) {
    var store = '';

    request.on('data', function(data) 
    {
        store += data;
    });
    request.on('end', function() 
    {  console.log(store);
        response.setHeader("Content-Type", "text/json");
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.end(store)
    });
 }  

and this on the client side:

$.ajax
({
  type: "POST",
  url: "http://localhost:8000",
  crossDomain:true, 
  dataType: "json",
  data:JSON.stringify({name: "Dennis", address: {city: "Dub", country: "IE"}})
 }).done(function ( data ) {
      alert("ajax callback response:"+JSON.stringify(data));
   })

Hope this works for you

You can't use response.write() or response.end() with a plain javascript object, you can only write Buffers or strings.

So what you need to do is stringify the object first. Either change the response.end(store); to response.end(JSON.stringify(store)); or don't store = JSON.parse(store); in the first place (unless you are doing it to validate the JSON -- and if that was that case you should wrap it in a try-catch because JSON.parse() will throw on parse error).

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论