2015-06-11 2 views
3

Я запускаю сервер узлов, на котором нет данных. Я хочу вывести данные на сервер, а затем снова забрать его нажатием кнопки. Я пробовал другие примеры, но я совершенно новичок в запросах 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'); 

Помогите. Спасибо!

+0

Почему вы используете jsonp? – B3rn475

+0

Поскольку серверы прослушивают localhost: 8080, а приложение работает на localhost: 3000. Чтобы делать запросы от одного к другому, вы должны использовать jsonp ... Я думаю. Как я уже сказал, я очень новичок в этом – CHeffernan087

+0

. Есть веская причина разделить приложение на два компонента? – B3rn475

ответ

2

Я реализовал сервер, чтобы служить вашим запросам отображения индекса html, сохранения пользователя на серверной памяти и отправки пользователю (хранящемуся на сервере памяти) клиенту.

Мой index.js файл выглядит следующим образом:

var http = require('http'); 
var url = require('url'); 
var querystring = require('querystring'); 
var fs = require('fs'); 

var server = http.createServer(); 

var userStoredInMemory = {}; 

// listening requests from clients 
server.on('request', function (request, response) { 
    var currentRoute = url.format(request.url); 
    var currentMethod = request.method; 
    var requestBody = ''; 

    switch (currentRoute) { 
    // serving the html index to client 
    case '/': 
     fs.readFile(__dirname + '/index.html', function (err, data) { 
     var headers = { 
      'Content-Type': 'text/html' 
     }; 

     response.writeHead(200, headers); 
     response.end(data); 
     }); 

    break; 

    // handling requests from client with route /api/user 
    case '/api/user': 
     // if request is a POST, then the user is sending a user 
     if (currentMethod === 'POST') { 
     // reading the body of the request 
     request.on('data', function (chunk) { 
      requestBody += chunk.toString(); 
     }); 

     // once the body of the request was loaded 
     request.on('end', function() { 

      // saving the user sent on the request body 
      userStoredInMemory = querystring.parse(requestBody); 

      // responding to the user 
      var headers = { 
      'Content-Type': 'text/plain' 
      }; 
      response.writeHead(200, headers); 
      response.end('User was already stored.'); 
     }); 
     } 

     // if request is a GET, then the client is requesting 
     // to see the user stored. 
     else if (currentMethod === 'GET') { 
     var headers = { 
      'Content-Type': 'application/json' 
     }; 

     response.writeHead(200, headers); 
     response.end(JSON.stringify(userStoredInMemory)); 
     } 
    break; 
    } 
}); 

server.listen(8080, function() { 
    console.log('server up and running at 8080 port'); 
}); 

А индекс HTML-файл выглядит следующим образом:

<!DOCTYPE html> 
<html> 
<head> 
    <title></title> 
</head> 
<body> 
<h1>Hello World!</h1> 

    <div> 
    <h1>Sending User</h1> 
    <form id="userForm"> 
     <label for="name">Name</label> 
     <input id="name" name="name"/> 
     <br/> 

     <label for="age">Age</label> 
     <input id="age" name="age"/> 
     <br/> 

     <input type="submit" value="Send"/> 
    </form> 
    </div> 

    <br/> 
    <br/> 

    <div> 
    <h2>Click the button below for getting User from server and showing it</h2> 
    <button id="getUserButton">Get User</button> 
    </div> 
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.js"></script> 
    <script> 
    $(document).ready(function() { 

     $('#userForm').submit(function (e) { 
     var user = { 
      name: $('input[name=name]').val(), 
      age: $('input[name=age]').val() 
     }; 

     $.ajax({ 
      type: 'POST', 
      url: 'http://localhost:8080/api/user', 
      data: user 
     }) 
     .done(function (data) { 
      // clear form 
      $('input[name=name]').val(''); 
      $('input[name=age]').val('') 


      alert(data); 
     }); 

     e.preventDefault(); 
     }); 

     $('#getUserButton').click(function (e) { 
     $.ajax({ 
      type: 'GET', 
      url: 'http://localhost:8080/api/user' 
     }) 
     .done(function (data) { 
      alert(JSON.stringify(data)); 
     }); 
     }); 
    }); 
    </script> 
</body> 
</html> 

Но посмотрите, как код и сложность уменьшается при использовании рамки когда вы создаете свой HTTP-сервер, в этом случае Express.JS, сначала установите express и body parser:

поэтому мой index.js выглядел так:

var express = require('express'); 
var app = express(); 

var bodyParser = require('body-parser'); 

var userStoredInMemory = {}; 

app.use(bodyParser.json()); 
app.use(bodyParser.urlencoded({extended: true})); 

app.get('/', function (req, res) { 
    res.sendFile(__dirname + '/index.html'); 
}); 

app.get('/api/user', function (req, res) { 
    res.json(userStoredInMemory); 
}); 

app.post('/api/user', function (req, res) { 
    userStoredInMemory = req.body; 
    res.send('User was already stored from express.'); 
}); 

app.listen(8080, function() { 
    console.log('server up and running at 8080 port'); 
}); 
+0

Спасибо! Я попробую! :) – CHeffernan087

+0

Я не знаю. Я скопировал ваш код точно, но он просто ничего не записывает на консоль или терминал (также нет предупреждений). Это так расстраивает! Сеть быстро делает себя врагом. Grrrrrrrrrrrrrrrrrrr – CHeffernan087

+0

Почему вы использовали localhost: 8080/api/user? – CHeffernan087