How to send json data from node js to html page - node.js

I have already get a serier of json data from facebook using node js express. Now I want to send the data to a html page. But I have no idea how to send the data and encode the data in html.

If you use Express in node.js, here is the way to send json object as response:
app.get('/test', function(req, res, next) {
res.json({ message: 'Hello World' });
});
Then in JS on your html page html, if you use jQuery:
$.ajax({
url: '/test',
complete: function(data) {
console.log(data);
}
});
Feel free to experiment with stuff, as well use Dev Tools in Chrome, experimentation - helps a lot to understand what and how it works.

Check out Heroku's example tutorial. I think it does exactly what you are asking for in terms of JSON encoding + throws in Web Sockets. https://devcenter.heroku.com/articles/node-websockets

Use res.json. For instance:
function(req,res) {
res.json({ user: 'tobi' })
}

Related

Postman oauth2 with nodejs

I'm want to test the oauth2 (nodejs) in postman.
So, I made this route:
router.get('/authorise', (req, res, next) => {
console.log('in authorise');
});
Postman, I set this Url (which point to my route):
It's work. It gets to this route. but I am not able to find how to close this window and get the token?
What should the response look like?
I searched everywhere on the web and could not find any information about it.
I have try this but still not working:
router.get('/authorise', (req, res, next) => {
console.log('in authorise');
res.writeHead(302, {
Location: 'https://www.getpostman.com/oauth2/callback?access_token=8ba64c1fbe8d4c3a892e432425842adde38fbb0e&response_type=code'
});
res.end();
});
You need to open the window from the client side not from the Node application and when you receive the response from Node you can close the window.
I Found!
Just need to return AUTHORIZATION_CODE like so:
res.redirect(url.format({
pathname: "https://www.getpostman.com/oauth2/callback",
query: {
code: `AUTHORIZATION_CODE`
}
}));
Then is continue to Access Token Url.

Rest api implementation with parameter using JetBrains WebStorm + node.js + express

First of all, i'm using JetBrains WebStorm and used to create the Node.js Express App project.
My modifications were at app.js
app.get('/api/restaurants', function(req, res) {
console.log("Parameter[0]", req.params.restaurant_id);
res.json({
'01010112D8139F13': '0ao123r1'
});
});
app.get('/api/restaurants/:id', function(req, res) {
console.log("Parameter[1]", req.params.restaurant_id);
res.json({
'message': 'worked?'
});
});
I'm using postman plugin at chrome to test my api and i can't access localhost:3000/api/restaurants?restaurant_id=01010112D8139F13 without being routed by router.route('/restaurants') instead of router.route('/restaurants/:restaurant_id')
At console i have:
GET /api/restaurants?id=01010112D8139F13 200 1.803 ms - 31
If anyone can help me, thanks in advance.
restaurant_id is not a query parameter but a variable part in your path. For example /restaurants/01010112 and /restaurants/1 are both handled by the same Web request handler because both fit on /restaurants/:restaurant_id pattern.
The restaurant specific endpoint need to be modified the following way:
app.get('/api/restaurants/:id', function(req, res) {
console.log("Parameter[1]", req.params.id);
res.json({
'message': 'worked?'
});
});
And use the following url on the console:
/api/restaurants/01010112D8139F13

can I create a route that could be use both for serving HTML and REST API?

Okay here's the scenario, to my knowledge there are three ways to create a web application
Traditional way: Render the HTML page from the server
Not sure: Create an API and let the user's browser to download the
Javascript application (Angular, React, Ember) to get a highly
interactive application
The future: Isomorphic web app, which render the HTML together with the client-side technologies (Angular, React, Ember) from the server.
I'm planning to use the third way, due to faster load page, but the problem right now is if I were about to create a mobile application.
My stack: Node.js + React
Let say if I'm planning to go mobile, do i need to duplicate the same route and logic ?
Current problem
app.get('/users', function(req, res) {
res.render('index', { message: "Hey Im Jack" });
});
app.get('/api/users', function(req, res) {
res.json({ message: "Hey Im Jack" })
});
Is there any way that I could use to for one route to serve both the HTML and REST?
You can ultimately only send either HTML or JSON (in case of REST).
The /api/xxx route syntax makes it clearer which path serves the JSON.
But you can depend on client's request header to check whether they requested JSON or HTML
app.get('/users', function(req, res) {
if (req.headers.accept && req.headers.accept.match(/json/))
res.json(data);
else
res.render('index', data);
});
Angular's $http usually requests json by default, not sure about others, but you can set the headers. Browsers normally request text/html, but I'm not sure.
Or if you're only concerned about not having to repeat the logic that fetches the data, you could put a middleware preceeding both:
// regex to match both routes
app.get(/.*users/, function(req, res) {
res.locals.data = { message: "Hey Im Jack" };
req.next();
});
app.get('/users', function(req, res) {
res.render('index', res.locals.data);
});
app.get('/api/users', function(req, res) {
res.json(res.locals.data)
});

Node.JS POST request to Express app secured by passport

Mechanism :
I am making this POST request to my API :
request.post('http://localhost:9876/api/alerts',{body: "test"}, function (err, res, body) {
if (err) {
self.emit('log','ERROR : API error - '+err);
}
self.emit('log','RESPONSE - '+res.statusCode);
});
On the server side, I have :
app.post('/api/alerts',function(req,res){
console.log(req);
res.status(200).send('OK');
});
Communication is made and it returns a 200 status. But on the server side, I see no trace of my request's body.
The full 'req' log is available here : https://gist.github.com/xShirase/0f9de0048e5cfa40a98c , the most relevant part being :
body: {},
I was wondering if it was coming from the Passport middleware that I use to secure the rest of my routes, or if I just botched the client request...
I have tried many different requests formats on the client side, and nothing has worked, and I have very little experience with Passport, so please let me know where my problem comes from.
Unless you have a (custom) middleware earlier up in the route/middleware chain that is doing something like:
app.use(function(req, res, next) {
var buffer = '';
req.setEncoding('utf8');
req.on('data', function(d) {
buffer += d;
}).on('end', function() {
req.body = buffer;
next();
});
});
then you probably shouldn't expect req.body to be populated since the common body parsing modules expect a Content-Type of one of application/json, application/x-www-form-urlencoded, or multipart/form-data. Your request() doesn't seem to be setting any of these, which really is correct since it's just free-form data, but that means no middleware is reading request data.

Angular Service to Express API Route + Posting Data

I am in the process of converting one of my sites (http://maskedarmory.com) from LAMP (using Laravel 4 MVC) over to the MEAN stack and it has been quite a journey thus far.
I have managed to get the landing page up and running and the input POSTing to Angular controller that I have it routed to.
Now, the problem I am having is getting the service to send over the POSTed data that is in Angular over to the Express API. I keep keeping a 404 Not Found error on the /api/character URL path.
Also, how do I access the 'characterData' variable that is on the Angular side that is being passed over by the factory? Because I am trying to do a console.log on the 'characterData' variable on the server side and I am sure that that is out of scope.
app/routes.js (Express Routing)
// public/js/services/ArmoryService.js
angular.module('ArmoryService', []).
factory('Armory', function($http) {
return {
// Get the specified character by its profile ID.
get : function(id) {
return $http.get('/api/character/' + id);
},
// call to POST and create a new character armory.
create : function(characterData) {
return $http.post('/api/character', characterData);
}
}
});
app/routes.js (Express Routing)
module.exports = function(app) {
app.post('/api/character', function(req, res) {
console.log(characterData);
});
app.get('/', function(req, res) {
res.sendfile('./public/index.html'); // load our public/index.html file
});
};
If I do a console.log before the $http.post to the API, 'characterData' has all of the information it should.
I am sure that this is a routing issue of some type, but I will be damned if I can figure it out.
Thanks in advance for your help!
Try this:
app.post('/api/character', function(req, res) {
console.log(JSON.stringify(req.body));
res.status(200).send('whatever you want to send back to angular side');
});
app.get('/api/character/:id', function(req, res) {
console.log(req.params.id);
res.status(200).send('whatever you want to send back to angular side'');
});

Resources