Я запускаю сервер узлов, на котором нет данных. Я хочу вывести данные на сервер, а затем снова забрать его нажатием кнопки. Я пробовал другие примеры, но я совершенно новичок в запросах ajax, и я хочу понять, что код, который я пишу, это что я до сих пор:Node.js Ajax Request
***script.js(Client file)***
$(document).ready(function() {
$.ajax({
url: 'http://localhost:8080',
dataType: "jsonp",
data: '{"data": "TEST"}',
type: 'POST',
jsonpCallback: 'callback',
success: function (data) {
var ret = jQuery.parseJSON(data);
console.log(data)
console.log('Success: ')
},
error: function (xhr, status, error) {
console.log('Error: ' + error.message);
},
});
$('#button').click(function(){
$.ajax({
url: 'http://localhost:8080',
dataType: "jsonp",
type: 'GET',
jsonpCallback: "callback",
success: function (data) {
var ret = jQuery.parseJSON(data);
console.log(data)
console.log('Success: Kick Ass!')
},
error: function (xhr, status, error) {
console.log('SOMETHING HAS GONE WRONG :(');
},
});
});
});
***Index.js(Server File)***
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');
Помогите. Спасибо!
Почему вы используете jsonp? – B3rn475
Поскольку серверы прослушивают localhost: 8080, а приложение работает на localhost: 3000. Чтобы делать запросы от одного к другому, вы должны использовать jsonp ... Я думаю. Как я уже сказал, я очень новичок в этом – CHeffernan087
. Есть веская причина разделить приложение на два компонента? – B3rn475