Reputation: 28783
I have the following client code (that runs in a browser or atom-shell/node-webkit Web API):
$(document).ready(function(){
$.ajax({
url: 'http://127.0.0.1:1337/users',
type: 'GET',
dataType: 'json',
success: function(res)
{
console.log(res);
}
});
});
Pretty simple stuff, it requests a list of users in JSON format from a server.
Now on the server end (Node API) I have the following code:
var http = require('http');
var mysql = require('mysql');
var connection = mysql.createConnection({
host : '127.0.0.1',
user : 'admin',
password : 'qwe123'
});
// Create the server
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('This is just a placeholder for the index of the server.');
}).listen(1337, '127.0.0.1');
// Build a response
http.get('http://127.0.0.1:1337/users', function(res) {
var json = { 'status' : res.statusCode, 'response' : res };
JSON.parse(json);
}).on('error', function(e) {
var json = { 'status' : e.statusCode, 'message' : e.message };
JSON.parse(json);
});
I've become confused as how to create the server and then effectively create endpoints (e.g. /users) that I can talk to via my client code.
1.) Am I right in thinking that http.get
only gets data from an already established endpoint? And that createSever
actual creates the endpoints? Or is there another shorthand method for creating these endpoints after the server has been created? So basically that get request isn't required in this example as I am wanting to request it client side.
2.) In any case I need to create this endpoint /users
and return the following:
connection.connect();
connection.query('SELECT * FROM users', function(err, results) {
JSON.parse(results);
});
connection.end();
Can anyone help point me back in the right direction? Seems like I've missed that part in the docs where you can create the different endpoints on your server.
Upvotes: 0
Views: 334
Reputation: 121
I am afraid you are mixing expressjs and node http module. If you are just using node "http", refer this: Nodejs to provide 1 api endpoint e one html page on how to achieve the routing of URL's.
All said, i would suggest you to take a look at the library expressjs for this: http://expressjs.com/starter/basic-routing.html. It largely simplifies the route management and provides much more functionality.
Hope this helps you.
Upvotes: 1