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
Related
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.
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)
});
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'');
});
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' })
}
I am using nodejs with express. I would like to return a custom 404 not found error page. I have it working. however I have not found a solution of how to return a error code with res.render(). I saw a few similar questions but they were old and using deprecated methods. Any help would be greatly appreciated.
check these:
app.use(function(req, res) {
res.status(404);
url = req.url;
res.render('404.jade', {title: '404: File Not Found', url: url });
});
// Handle 500
app.use(function(error, req, res, next) {
res.status(500);
url = req.url;
res.render('500.jade', {title:'500: Internal Server Error', error: error, url: url});
});
I cannot find confirmation in Express docs but using:
res.status(statusCode).render(page)
Status and render the page correctly.
express: "4.17.1"