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.
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.
Related
I want to send the variable from javascript to node js
here I am storing some data in my javascript variable
var roomurl = "this is the data";
And here is my nodejs code
app.post("/newcall", function(req, res) {
var n = (req.body.roomurl);
console.log("val"+ n);
});
I have included all the dependencies like express and body parser
but I am not how to send it
can I get help in my javascript code or
any Url from where I can get to now about how do
I send data from java script to node js ?
thanks
Actually, you should run the node/express application to a specific port, ex 3000
app.listen(3000, () => {
console.log('App running at 3000')
})
Then from your client you should post your data via Fetch API or another http client like this
fetch('http://localhost:3000/newcall', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({roomurl})
});
I'm an absolute beginner in nodejs. I've created an echo server in nodejs. And honestly i would say, i followed few youtube tutorials for this. There is nothing wrong with the server code. I want to create a client program to talk to this server. I dont want to use telnet client or any such thing. And by 'continuous' I mean the server and client should stay connected till I close the server manually using ctrl+c. Here's my server.js.
const express = require('express');
const bodyParser=require('body-parser');
var server=express();
server.use(bodyParser.urlencoded({extended: false}));
server.use(bodyParser.json());
server.post("/", function (req, res) {
console.log("I got: "+req.body.message);
res.send(req.body.message);
});
server.listen(3000, function() {
console.log("Express echo server is listening on port 3000");
})
I do not say hey write the code for me. In fact I tried also. Here's my client.js
var request = require('request');
var arg="";
process.argv.slice(2).forEach(function (val, index, array) {
arg+=val +" ";
});
request.post({
url: "http://localhost:3000",
json: true,
body: {message: arg}
}, function (err, response, body) {
if(!err && response.statusCode==200) {
console.log(body);
}
});
But client sends data only once that too using command line argument.
node client.js hello
PS: I'm using these npm modules express, body-parser and request
What you made is a HTTP Server using express.
The server runs alright, but the client closes because you are only making a single request to the server. So what is happening is expected behaviour.
So, there are multiple ways,
The most simple way would be, using readline or some other to continuously read the lines that you type And sending it to the server:
const request = require('request');
const readline = require("readline").createInterface({
input: process.stdin,
output: process.stdout
});
readline.setPrompt('msg: ');
readline.prompt();
readline.on('line', function(input) {
if(input === 'close') return readline.close();
request.post({
url: "http://localhost:3000",
json: true,
body: {message: input}
}, function (err, response, body) {
readline.prompt();
});
}).on('close', function() {
console.log('Closed');
process.exit(0);
});
But the proper way would be using sockets like socket-io to make a persistent connection between the server and client. Read here for more information.
I am trying to create a web app with some drop down menus that contain data from a sql server database. After some searching I figured out how to use node.js to output the table data into the command prompt.
var sql = require('mssql/msnodesqlv8');
var config = {
connectionString: 'Driver=SQL Server;Server=NAME\\SQLEXPRESS;Database=master;Trusted_Connection=true;'
};
sql.connect(config, err => {
new sql.Request().query('SELECT * FROM TABLE', (err, result) => {
console.log("Works");
if(err) { // SQL error, but connection OK.
console.log(" Error: "+ err);
} else { // All good.
console.dir(result);
};
});
});
sql.on('error', err => { // Connection bad.
console.log("Bad");
console.log(" Error: "+ err);
});
Now the problem is I don't know how to get that result into JSON data that can be used in my web app. Any help would be appreciated as I am quite new to node.js. Thanks!
EDIT:
Thanks for the help so far! I added the following code for when there is no error:
var express = require('express')
var app = express()
JSON.stringify(result);
console.log(JSON.stringify(result));
app.get('/', function (req, res) {
res.send(result)
})
I also have all of the code for the http server but I don't think it's necessary to show it all. Is this all that is needed on the server side?
First of all, to send data from the server to the client you'll have to run an HTTP server as part of your Node backend. Then, once the web app loads, it should make a request to your server, which as a response will return the data from the database. For more information on how to do this check out Express (for the server side) and Fetch API (for the client side).
Despite I have learned and implemented AJAX request with Node on my local server. I am finding that the requests that I created on my local server, just does not work at cloud server.
When I use AJAX to request data to the server (Node), the request does not get to the server because of the URL (or I think so).
Node Code:
app.get("/",function(req,res){
app.use(express.static(__dirname + '/'));
app.get("/mypath/",function(req,res){
console.log("please tell me that you arrive here"); //This actually never happens
//some functions using the data in "req" and putting there in var "data"
res.send(data);
});
});
Javascript Code:
$.ajax({
url: 'http://localhost:3000/mypath/',
type: 'GET',
data: {//some data to use on the server},
dataType: "json",
complete: function(data){
//some stuff with the transformed data
},
});
The code above works in the local server (my pc). But not in the cloud one, I had some problems trying to the server static files with NGINX and Express, but I was able to figure it out.
Do you think that given the way I am serving the static files and that I am working in the cloud server, I should use AJAX request in a different way when we are trying to communicate through an URL?
Console Log:
Console Log after using Marcos solution
EDIT: Code from jQuery AJAX and Node Request
Node Set-Up:
var express = require('express');
var app = express();
var request = require("request");
var db = require('mysql');
const path = require('path');
var http = require("http").Server(app);
var io = require("/usr/local/lib/node_modules/socket.io").listen(http);
http.listen(3000, 'localhost'); //At the end of everything between here and the code.
GET Node Code:
app.use(express.static(__dirname + '/'));
app.get('/reqData',function(req,res){
//I never arrive here
console.log("print that I am here");
transform(req.query.selection1,req.query.selection2,function(){
res.json(data); //data is transformed globally
});
});
Ajax:
function requestData(){
$.ajax({
url: 'http://localhost:3000/reqData',
type: 'GET',
data: {//Some stuff to send},
dataType: "json",
complete: function(data){
do(data);
},
error: function(e){
console.log(e);
}
});
}
New Console Log:
Chrome Console Error
The main issue you have, is how you're defining your routes, you will be unable to reach /mypath/ until you perform a request first to /.
You should not define your routes that way, each route should be defined individually, and not in a nested way.
app.get('*', (req, res, next) => {
// Set your cookies here, or whatever you want
// This will happen before serving static files
next(); // Don't forget next.
});
app.use(express.static(__dirname + '/'));
app.get('/mypath/', (req,res) => {
console.log("please tell me that you arrive here"); //This actually never happens
//some functions using the data in "req" and putting there in var "data"
res.send(data); // make sure it is defined.
});
And your route app.get('/') conflicts with express.static(__dirname + '/'), so you should just remove it if you're only serving an index.html file, which seems to be your case.
Then in your $.ajax you should add the protocol to the URL.
$.ajax({
url: 'http://yourdomain.com/mypath/',
// url: 'http://localhost:3000/mypath/',
/* ... */
});
Now, supposing you have everything else setup correctly, you will be able to access /mypath
In Node JS, how do i create an endpoint pass through?
I'm using express and http
The entire app will be a just a series of pass through endpoints.
Here is my code
// the real endpoint is somewhere else.
// for example http://m-engine.herokuapp.com/api/getstudents2
var http = require('http');
var options = {
host: 'http://m-engine.herokuapp.com',
path: '/api/getstudents2',
method: 'GET'
};
app.get('/api/getstudents', function(req, res){
// now past the request through
http.request(options, function(response2) {
response2.on('data', function (data) {
res.json(data);
});
}).end();
});
You can make use bouncy or node-http-proxy module for node.js to achieve the same thing.
Here is the sample code for bouncy:
var fs = require('fs');
var crypto = require('crypto');
var bouncy = require('bouncy');
bouncy(function (req, bounce) {
bounce("http://m-engine.herokuapp.com");
}).listen(8000);
Although, you can achieve the same thing with help of nginx also. No need to create node service for the same thing. Search on google for nginx proxy_pass. You can get examples for the same.