Node.js and Express not working? - node.js

I am currently trying to learn implementing RESTful APIs using Node.js & Express. Using this tutorial: http://code.runnable.com/U7bnCsACcG8MGzEc/restful-api-with-node-js-express-4
I created each file on my local drive and tried running the code using node server.js..However I kept on getting an error. Why might be causing this?

The code you chose to run is only routing requests for urls that begin with /api as you can see here:
app.use('/api', router);
On top of that, the routes it accepts are /players and /player/:id:
router.get('/players', function(req, res, next) {
res.json({ players: players.getAllPlayer() });
});
router.get('/players/:id', function(req, res, next) {
var player = players.getPlayerById(req.params.id)
res.json(player);
});
For every request, including the routes above, it outputs the method and url to console.log.
Even when it fails to get /, you should see GET / in your console.
Now try to access this url: 0.0.0.0:8080/api/players
It works, right?

Related

express.js PUT method doesn't run properly

I am making a simple project for practicing node and express. My GET methods work with no problem but my PUT method doesn't run. I don't know why nor how to fix it.
I tried putting my PUTmethod before my GET methods but it doesn't change a thing.
app.get("/", (req, res)=>{
res.send("Welcome to our website");
});
app.get("/animes", (req, res)=>{
res.send(dataFile.animes);
});
app.get("/animes/:id", (req, res)=>{
res.send(dataFile.animes[req.params.id]);
});
app.put("/update", (req, res)=>{
console.log("hello");
});
On the browser it keeps showing "Cannot GET /update"
To perform PUT and POST requests you would need a client supporting the method; if you try it in the browser, it will perform a GET by default, that's why the browser displays: "Cannot GET /update".
If you want to consume the PUT you would need a client like CURL https://curl.haxx.se/ or Postman https://www.getpostman.com/.
If you have CURL and the server is running in the port 3000 it would be:
curl -X PUT localhost:3000/update

How to avoid my route to call twice?in Nodejs

my route is calling twice,am using express, I have checked some link related to this
node.js page refresh calling resources twice?
so i have added console.log(req.url),
My output is
Hi..
/
Hi..
/
My code:
app.get('/', function (req, res) {
console.log("Hi..")
console.log(req.url)
});
How do i solve this issue?

How to use authenticated middleware properly in nodejs

I just started working on node using express framework.
app.use('/', auth, users);
and this is my route file
router.get('/' , function(req, res, next) {
render("dashboard");
});
router.get('/first' , function(req, res, next) {
//first request
});
router.get('/second' , function(req, res, next) {
//second request
});
so on...
My question is, when i pass middleware it checks for every request whether its authenticated or not using passportjs, but suppose i have a dashboard and i am sending 10 ajax requests to grab data for the widgets. So only for dashboard it will call deserialize function 11 times ,first to render the page and then for 10 ajax request. I read answer given over here,
How to properly use Passport.js?
But is it fine to go with this approach?
Yes, it is fine to go with this approach if you don't want to have security issues. You have to check the user for every request, it is very simple someone to check the network tab in the browser debugger, understand what's going on and then start spoofing your requests. You can't sacrifice security for performance because you want to execute few query less.

Prerender.io not caching pages

I have made an app with AngularJS with an expressJS backend. Now I want to make it crawlable and I've found prerender.io. I think I've done everything correct bur for some reason I don't see any statistics in the prerenderer dashboard.
In my app.configure function I've included the token like follows:
app.use(require('prerender-node').set('prerenderToken', 'my-token'));
And in my HTML I've included the meta-fragment tag:
<meta name="fragment" content="!">
The last ting I've done was to tell AngularJS to use a hashprefix:
$locationProvider.html5Mode(false);
$locationProvider.hashPrefix('!');
But for some reason, if I refer to the documentation, I don't get the correct result. Below you can see what it is supposed to do:
Google sends a request to your server like this:
http://www.example.com/?_escaped_fragment_=/user/123
You turn the url back into this:
http://www.example.com/#!/user/123
For some reason if I try this it still adds the #! signs add the end of the URL, so if I request the URL of my app like google I get this:
http://www.my-website.com/?_escaped_fragment_=#!/home
So it does not replace the hash in the url. I think this is the cause of my problem.
Thanks in advance!
Edit - if I for example add an extra route then it works:
app.get('/', function (req, res) {
res.sendfile('./public/index.html');
});
app.get('/test', function (req, res) {
res.sendfile('./public/index.html');
});
the '/' route doesn't work the '/test' route does work.
Ok I solved my problem. The '/' route was never called because I had an index.html file inside my webpublic folder. I renamed this to public.html and changed the '/' route to get this file instead of the index.html file.
app.get('/', function (req, res) {
res.sendfile('./public/public.html');
});

properly handle a 404 in expressjs

A little baffled at how to best handle 404 cases in my app. Here is a gist of a very basic example.
//******************************
// BUILD THE HTTP SERVER
//******************************
var express = require('express');
var app = express.createServer();
app.get('/login', function(req, res){
console.log("hit the login");
res.send('you hit the login');
});
app.get('*', function(req, res){
console.log("got a 404");
res.send('what???', 404);
});
app.listen(8081);
console.log('Server started on port: 8081');
If I fire up the server and hit the index of the server "/" I properly get the 404 message, HOWEVER, in the logs are 2 "got a 404" log entries on the console... odd.
So if I hit the "/login" page I do get the proper page, and corresponding message to the console, BUT, I ALSO get the 404 message to the console too?
Is this the expected behavior? I am using the latest 2.5.4 express on 4.11 but have tried it on other versions of node with the same results.
I dont really like the fact that my 404 route gets called on every single request, I must be doing something wrong.
This is probably due to fact that browser trying to get also favicon for your page.
Just use express.favicon() creating your server:
express.createServer(
express.favicon()
);
You may also want to use logger to discover thing like this, it's really useful middleware.

Resources