Send JSON data from express to html NodeJS - javascript

Hello all i'm new with node so here my use case i want to post data to my express app and show it on a html page is that possible with nodeJs ?
Here my code
app.post('/', function(req, res){
res.sendFile(__dirname + '/views/index.html', {data: req.body});
})

There are many tutorials showing how to do that. I would recommend first you understand how HTTP protocol works (The message structure : https://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html). Then go dive into node and exchange data through requests and responses. I'd recommend body-parser to arrange the data format between the two sides. Also read the express documentation. Hope it helps.

Related

How to access POST data in express js?

Im using (in the browser):
xmlHttp.open("POST", "/", true); // true for asynchronous
xmlHttp.send("data");
on the client side browser.
I'm using (node js):
app.post("/", function (req, res) {
console.log("Got a POST request");
console.log(req);
});
to get the post data. but it doesn't matter what I send it doesn't show up.
I don't wanna have to install some separate "body parser" package to see the data.... I don't wanna parse it. A post request is used to send data to the server... is the data just not there?
I don't wanna have to install some separate "body parser" package to see the data.... I don't wanna parse it.
Too bad.
Even if you want to process a plain text body then you need to use body parsing middleware to do it.
One of the responsibilities of the middleware is to take the stream of data from the client and store it in memory (assigning it to req.body) instead of discarding it.
Note that body parsing middleware is installed automatically as a dependency of Express.js itself.
There is no need for a separate body parser library. You can use express.json. It
is a built-in middleware function in Express. You can use it like:
app.use(express.json())
You can read more about it here.

Communication between an express node server and its displaying html

Really fast, this question may have already been asked, but I am not totally clear on the terminology and have had no success when searching for a solution.
I am attempting to create a simple web application that can receive get and post requests. Then, I would like to take the information I receive from these requests and use them in a javascript file embedded in html that is displayed. I think it may be more clear with code. This is my app.js:
var express = require('express');
var app = express();
var assert = require('assert');
app.use(express.static('javascript'));
app.get('/', function(req, res) {
res.render('index.jade');
});
app.listen(3000);
I would then like to be able to take information received from a get or post request, specifically in JSON format, and then be able to use it in javascript that I have linked to index.jade. To make matters slightly more confusing in index.jade the only line is:
include map.html
So ideally I would be able to get the information to javascript in that html file.
I want to be able to pretty continuously update map.html using javascript based on frequent get and post commands.
This could be a very simple solution, I am pretty new with web application programming in general, and I have been struggling with this problem. Thanks in advance, and ask if you need any clarification.
I think you need to understand what you are doing. You are creating a web server using node.js. Express framework simplifies that for you. The official documentation of express is pretty great. You should refer that especially this link.
Now, in your application, you need to create endpoints for GET and POST requests. You have already created one endpoint "/" (root location) that loads your home page which is the contents of the file index.jade. A small example is :
app.get('/json', function (req, res) {
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify({ a: 1 }));
});
Jade is a templating engine which resolves to HTML. You should refer its documentation as well. Since as you said, you are not very familiar with these, you could simply use HTML as well.
After this tasks are quite simple. In your javascript, using ajax calls you can access the GET or POST endpoints of your server and do the desired actions.
Hope it helps!
The way I get it you want to be able to call an endpoint (lets assume /awesome) pass some info and then write to a Javascript file that you can then reference in your html.
Something like the below would write a main.js file in your public folder. You can make it write whatever you want.
var fs = require('fs');
fs.writeFile("/public/main.js", "console.log('Hello!')", function(err) {
if(err) {
return console.log(err);
}
console.log("The file was saved!");
});
You can then reference /public/main.js in your html.
Check that: Writing files in Node.js
If I misunderstood your intentions, apologies. :)
So you want to reviece continuously data from the server maybe web sockts are an option for you http://socket.io/docs/
This way u will open a stable connection from the client to the server. This is a great way if u want to get updates done by other clients.
If you want to trigger the changes by the client then ajaxs calls(http://www.w3schools.com/ajax/) as hkasera mentioned are the way to go.

Node.js - passing values to other pages

I'm trying to build a web service using node.js.
In this architecture, curl is used to POST data to the index.js app. The index.js app process the output and then it should pass the output to different pages.
For example, if the ID received is between 100-200 then push the ID to movies.html and so on.
Now I have been able to achieve the processing of POST request using CURL and node.js
I have no idea how to pass the data to other pages.
Here is my index.js code.
var http = require('http');
var qs=require('querystring');
var redis=require('redis').createClient();
console.log('Server Starting Now: ');
var count=0;
http.createServer(function (req, res) {
if(req.method=='POST'){
count=count+1;
var body="";
req.on('data',function(data){
body+=data;
});
req.on('end',function(){
var post=qs.parse(body);
console.log(post);
res.write("Received");
redis.lpush('XMLqueue',JSON.stringify(post));
});
}
}).listen(8124, "127.0.0.1");
console.log('Server running at http://127.0.0.1:8124/');
How do I pass the data from this index.js page to other pages?
Create handlers for other URLs which will respond with the data you want it to.
But actually, you seem to be confused by nodejs and overall http server architecture a lot. I'd suggest you to read any "getting started nodejs" tutorial you find at Google and like to get the basics. Also, search for something like "nodejs express" and reading it will probably help you to get an easy start.

Send URL string to other script with Node.js

I am starting to learn Node.js, using Express with Jade and Mongoose as my default toolbox. I used to develop in PHP, migrated to Python, and learned MVC through Django. Having a large client-side JS game and some inspiration from Mozilla.org, I am willing to make a multiplayer game -- and saw this as a noncommercial opportunity to learn Node: I can take my time with it.
However, I ran into a problem. I'm not trying to write an MVC system on my own, just to separate my site's "apps" like most MVCs do. The question is probably basic -- having this chunk of code:
app.get(/^blog/, function(req, res) {
require("./blog")();
});
... I understand the basics of Node/Express' URL masking, however I need to pass the rest of the URL string (everything that's after mysite.com/blog) to another URL parsing script, inside the blogapp.
I googled around for a while and couldn't find a good solution. I even found a full tutorial on building an MVC scheme in Node and Express written for an older Express version, but that's a bit over the top for now. Can you provide me a simple solution?
I think blog/index.js should look something like this:
module.exports = function(urlstring) {
if(urlstring.indexOf('post') != -1) {
// do stuff...
}
else if(urlstring === '/') {
// return home.jade or something
}
};
I hope I'm being clear. Thanks in advance!
With express there is no need to parse your URLs on your own. I guess you'll want to build your blog URLs somehow like this
/blog Show a list of blog posts
/blog/post/1 Show blog post with id '1'
With express 4 you can set up a router for your blog path or a mounted app. Mounted apps allow you to let an app handle all sub URLs of a base URL path. See the express documentation for more detail.
I'd like to demonstrate how you can use the express 4 router together with the mounting feature of express to build blog routes.
// Set up express app
var app = express();
// Set up a router
var router = express.Router();
router.get('/', function(req, res) {
// Show a list of blog posts
}
router.get('/post/:id', function(req, res) {
// Show a single blog post
}
// Mount router
app.use('/blog', router);
A benefit of this solution is that your routes registered in the router always get relative URLs with out the /blog prefix so you may reuse your blog routes in some other project under a URL like /companyblog.

node.js how to respond .js files with parameters

I have a node.js http application and i'm servicing GET requests ok. I can't however respond properly with requests for say foo.js?_param=1234. How do i deal correctly with files of this type where parameters are being passed?
EDIT:
I'm using express to service files as follows:
app.get('/*', function(req, res) {
res.sendfile(__application+req.url, {root: __root});
});
__root is the root path of the application.
Use request.url, it will look like /foo.js?_param=123.
Then use require('url').parse(url,true) to split this into meaningful parts (true is to also expand individual query string parameters).
See http://nodejs.org/api/http.html#http_request_url for details.
Try using the express module.
They have a whole API for dealing with GET and POST requests.
You can use req.query to handle the get requests.

Categories

Resources