1

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

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');

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>

But I am getting this error:

"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)

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.

4
  • Seems you have some malformed JSON. What does your JSON look like? Commented Jan 4, 2019 at 4:04
  • @RobertHarvey this is JSON data I wanted to send : '{ "name":"John", "age":30, "car":null } Commented Jan 4, 2019 at 4:07
  • Seems legit. So why is JSON.parse seeing the character 'c' at the very first position in your JSON string? Commented Jan 4, 2019 at 4:08
  • @RobertHarvey that's my question :-) why? Commented Jan 4, 2019 at 4:15

1 Answer 1

2

Your ajax request should be like this

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

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\"}\')');
}
Sign up to request clarification or add additional context in comments.

3 Comments

Explain why this works, and why the OP's code doesn't.
@Sanjaysinh It's happening thanks for your quick solution. Now how can I save JSON data to local file?
I added 'let data1 = JSON.stringify(body); fs.writeFileSync('text.json',data1);' But it's copying only " " in json file

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.