Я хотел отправить данные JSON на сервер node.js.
Это мой server.js:
var http = require('http');
var util = require('util')
http.createServer(function (req, res) {
console.info('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.info('GOT DATA!');
});
res.end('callback(\'{\"msg\": \"OK\"}\')');
}).listen(8090);
console.info('Server running on port 8090');
Это html-файл:
<!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.info('Success: ')
},
error: function (xhr, status, error) {
console.info('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. И если я получу данные, я хочу сохранить их в локальном файле.
@RobertHarvey, это данные JSON, которые я хотел отправить: '{"name": "John", "age": 30, "car": null}
Выглядит вполне законно. Так почему же JSON.parse видит символ c в самой первой позиции в строке JSON?
@RobertHarvey, это мой вопрос :-) почему?





Ваш запрос ajax должен быть таким
$.ajax({
url: 'http://127.0.0.1:8090/',
data: { "name": "John", "age":30, "car":null },
type: 'POST'
.....
})
И в методе createServer server.js обновите это
if (req.method == 'POST') {
console.info("POST");
var body = '';
req.on('data', function (data) {
body += data;
console.info("Partial body: " + body);
});
req.on('end', function () {
console.info("Body: " + body);
});
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('callback(\'{\"msg\": \"OK\"}\')');
}
else
{
console.info("GET");
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('callback(\'{\"msg\": \"OK\"}\')');
}
Объясните, почему это работает, а код OP - нет.
@Sanjaysinh Это происходит, спасибо за быстрое решение. Как теперь сохранить данные JSON в локальный файл?
Я добавил let data1 = JSON.stringify (body); fs.writeFileSync ('text.json', data1); ' Но он копирует только "" в json файл
Кажется, у вас неправильный формат JSON. Как выглядит ваш JSON?