Node js router 404 with params - javascript

I wanna pass parameter to page. But have 404. My code:
app.js
var routes = require('./routes/index');
var app = express();
routes/index.js:
var express = require('express');
var router = express.Router();
router.get('/profile/:id', function (req, res) {
var id = req.params.id;
console.log(id);
res.render('profile', {id: id});
});
and i try http://localhost:3000/profile?id=56e2c3c2cdde3f64302ac154 but have Error: Not Found

Your route should be looks like:
http://localhost:3000/profile/56e2c3c2cdde3f64302ac154
It is automaticaly set req.params.id.

There is a difference between Path param and Query param . The Url you have defined
/profile/:id
Says to the routing framework that , I expect id as Path param i.e part of the resource path . But in the url request you made
http://localhost:3000/profile?id=56e2c3c2cdde3f64302ac154
You are sending id as query param . So the routing framework is unaware of the url with id as a query param . Hence it returns a 404 meaning "the server could not find what was requested" .

Related

Execution flow when a request hit a node js server

I'm new to Nodejs and here I have a piece of code in app.js :
var config = require('./config')
, express = require('express')
, db = require('./app/lib/db')
, utils = require('./app/lib/utils')(config, db)
var app = express()
http = require('http').createServer(app)
require('./config/express')(app, config)
require('./config/routes')(app, utils, model_list)
http.listen(config.port, function () {
console.log("API running at http://" + config.hostname)
})
And a list of router api are set up in the file config/routes, for example:
app.get('/api/' + name + '/:limit([0-9]+)/:page([0-9]+)', ctrls[name].list); // get list with page
app.get('/api/' + name, ctrls[name].list); // get list with default page = 1
app.post('/api/' + name + '/search', ctrls[name].search); // search
app.get('/api/' + name + '/:id([0-9a-f]+)', ctrls[name].get); // get by id
After the server is created and starts to listen to the config port, what is the execution flow of a new request when it hits the server? How can the server catch a request in app.js and then move to routes.js to route it to a function to handle it?
It does not move to routes.js... routes.js is required inside app.js and it applies the routes to the app object which is the express server. That is done once, before the server starts listening to port.
How express routes the request when it receives one is completely done internally. Basically it will check the request method (GET, POST, etc) then will check the requested URI and try to match a route, if the route matches, the function is executed.
you should check the anatomy of http in nodejs.
https://nodejs.org/en/docs/guides/anatomy-of-an-http-transaction/

How to redirect to another web service with data and header in nodejs

I am creating rest web service using express nodejs framework. I want to navigate to second.js page from first.js and need to send data and header to it.
first.js
const express = require("express");
const http = require("http");
var router = express.Router();
var options = {
host: "localhost",
port: "3000",
path: "/second",
method: "POST"
};
router.get("/", function(req, res, next) {
http.request(options);
});
module.exports = router;
second.js
var express = require("express");
var router = express.Router();
router.get("/", function(req, res, next) {
res.send("Hello");
});
module.exports = router;
app.js
app.use("/first", first);
app.use("/second", second);
I tried like above but it doesn't navigate to second.js web service. Does anyone know what I am doing wrong ?
Your code is not performing a redirection. You are actually making a call from within the first endpoint to a second endpoint and acting more like a proxy.
A redirection is performed by calling res.redirect as defined in the express documentation at http://expressjs.com/en/api.html (Search for res.redirect). A redirection returns a HTTP redirect response that the users browser will follow to a new URL. Unfortunately, redirections do not allow headers to be passed and it will be executed as a GET call(This is what redirections are designed for.). You can include whatever query params you want in the URL though and set cookies (refer to How to forward headers on HTTP redirect)
I think you are using POST in your request
But only set up GET on your second endpoint

App.js GET url parameter and send to routes/index.js

Here is my url: http://localhost:3000/?url=test
I'm running a Express so in my app.js I'm trying to get a the url parameter "test" send it to my routes/index.js
I'm sending a static variable no problem by using:
code in app.js
app.locals.url = 'a test string';
and receiving in my routes/index.js
var url;
url = req.app.locals.url;
Any idea how in app.js I can have:
app.locals.url = {the parameter "test" in the http://localhost:3000/?url=test}
Thanks!
You are trying to refer the query parameters in a false parameter.
While using Express.js, we refer to the parameters sent with GET request in the following manner -
var url = req.query.url; //url is the parameter sent - localhost:3000/?url=www.google.com
With express, you can use req.query
req.query.url
// => "test"
A representation of the HTTP request is passed to the callback function of most methods. This object will have property query, which will contain a property for each query string in the HTTP request.
app.get('/', function(req, res) {
url = req.query.url; // For http://localhost:3000/?url=test, val => 'test'
});

express error - cannot find module - static file

I keep getting an error that says it cannot find the module reddit.js. I have a folder called "routes" (without quotes) in my directory. In that folder I have reddit.js which is middleware. On the first file below, I did change it to var reddit = require('./routes/reddit.js') and I received the error messsage that says "throw new TypeError('Router.use() requires middleware function but got a
^
TypeError: Router.use() requires middleware function but got a Object
at Function.use "
When I keep the code as shown below I get this error:
Error: Cannot find module 'reddit.js'
my app.js file contains the following code:
var express = require('express');
var app = express();
var fs = require('fs');
var reddit = require('reddit.js');
app.use ('/', reddit);
app.use(express.static('public'));
app.use(express.static('public/js'));
app.use(express.static('public/images'));
app.use(express.static('routes'));
my reddit.js file contains the following code:
var express = require ('express');
var request = require ('request');
var reddit = express.Router();
reddit.get(function (req, res, next) {
request('https://www.reddit.com/r/Showerthoughts/hot.json',function(error, response, body){
console.log(body);
var docs = JSON.parse(body).response;
//var titles = [];
console.log(docs);
res.send(docs);
next;
});
});
what am I doing wrong?
Mentioned below are the list of things that are not correct
You don't need to have .js extensions for including files. Use require('/path/to/reddit'); instead of require('reddit.js');
You need to export the router instance in reddit.js. Add module.exports = reddit; at the end of the file.
Don't call next() after sending out the response using res.send(docs);
Routes are not static content. Remove app.use(express.static('routes'));
app.use(express.static('/public')); handles all static content inside the /public folder. You do not need to add app.use(express.static('/public/js'));

express node.js making a get request to another server from node route

So the client makes a get request using a button on the index page. This sends some information to a route which has been set up as follows:
app.js
var route = require('./routes/index');
var button = require('./routes/button');
app.use('/', index);
app.use('/button', button);
The request is sent from a client-side directory to the node framework whenever someone presses the button. If the request is sent to 'localhost:port/button', then the button.js file mentioned above will receive the request. So in the button.js file we have something like the following:
var express = require('express');
var router = express.Router();
var someData = '';
router.get('/', function (req, res, next) {
//make a get request here such that someData
//receives whatever the request returns from another
//set up framework(i.e. Spring...)
someData = getRequest('some other URL');
res.send(someData);
};
module.exports = router;
The problem here is that the getRequest('some other URL') within the router get request never receives any information.
Also (as a side-note), I cannot seem to find in the express API as to why we have
router.get('/')...
instead of
router.get('/button')...
to access and make requests to the button page.
Any help would be very much appreciated!
You want to make a request to some other REST API running somewhere else right?
You can use node-rest-client for that.
I guess you are confusing what is server code and client code or do I´m missing something?
I´ll try to explain the way it works:
Server code:
var express = require('express');
var router = express.Router();
var someData = '';
router.get('/yearStations/:id', function (req, res, next) {
//make a get request here such that someData
//receives whatever -the id parameter- the request returns from another
//This is express.js
someData = getYourDataFromDataBase(req.params.id);
res.send(someData);
};
module.exports = router;
Client code:
JS (angular.js)
$scope.getInfo = function() { //here you make the GET call to the server
$http.get("http://localhost:XXXX/yearStations/Spring").then(
function(success){
alert(success.data);//this should be your data
});
};
HTML
<button ng-click="getInfo()">getInfo</button>

Categories

Resources