A simple http GET request doesn't hit the express js api - node.js

I have a simple node/express js api that receives request from another app.The request is this GET /api/users?data=5. Whenever i hardcode data with 5 like above, it does hit /api/users route.But whenever i send the request with dynamic data like GET /api/users?data=id where id = 5, it DOESN'T hit /api/users route, But in the server logs i do see the request did hit with url /users?data=5.I am not sure whats wrong but i am suspecting maybe i didnt define the routes correctly.Any help will be appreciated.Sorry I am new to Node js. Thank you.Here is my code
var app = express();
var router = express.Router();
router.use(function(req, res, next) {
next();
});
router.get('/', function(req, res) {
res.render('home');
});
app.use('/api', router);
router.route('/users')
.get (function(req, res) {
var data = req.query.data;
});

I figured it out , in the request GET /api/users?data=id HTTP/1. id was not properly formated ,hence the request was hitting the server but not application layer.
UPDATE
In short the app that make Http GET request is written in arduino (which translates it to C).I was reading the ID from the device memory which is saved as char array.So i thought i had converted the char array to string but in reality was still chars, and i put this variable in the url for Get request that is why it was complaining.

Related

cannot get POST request on express

I can't get any POST requests with the express framework.
This is my code
var express = require("express");
var app = express();
app.set("view engine","ejs")
app.get("/", function(req, res){
res.render("home");
});
app.post("/addfriend", function(req, res){
res.send("you have reached the post route succesfully");
});
app.get("/friends", function(req, res){
var friends =["lara","tommy","miranda","faith","locas"];
res.render("friends",{friends : friends});
});
app.listen(3000, function(){
console.log("server is listening on port 3000");
});
any suggestion please.
Few observations.
1)You are missing body parser for your app.js ( if in future you want to read form data).
just add this to your app,js
const app = express();
app.use(bodyParser.json());
Wherever you are using trying to send post request for example a HTML form or a button does it have correct route, it should match with this post route /addfriend.
Browser always send get request to server from browser, to specifically send post request use postman, curl or a HTML form.
If you are using postman try this https://learning.postman.com/docs/sending-requests/requests/#sending-body-data
For the difference between get and post follow this
Edit :-
Http post request means :- "The HTTP POST method sends data to the server. The type of the body of the request is indicated by the Content-Type header."
get request :- "The HTTP GET method requests a representation of the specified resource. Requests using GET should only be used to request data (they shouldn't include data)."

request header can't get cookie when using res.cookie of Express 4.x

i just want to try basic methods to set cookie and show in request head.
front-end is just a basic html form with username and password text input, use POST method to transfer data.
below is code based on express.
server just receive req.body, then set it as cookie with domain: localhost:1338/base
cookieRouter.js:
var express = require('express');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var router = express.Router();
router.use(bodyParser.urlencoded({ extended: false }));
router.use(cookieParser());
router.get('/', function (req, res) {
res.send('this is a router base page!');
});
router.get('/index1.html', function (req, res) {
res.sendFile(__dirname + '/index1.html');
});
router.post('/index1.html', function (req, res) {
res.cookie('name', req.body, { domain: 'localhost:1338', path: '/base' });
res.send(req.body);
});
module.exports = router;
app.js
var express = require('express');
var app = express();
var cookieRouter = require('./cookieRouter.js');
app.get('/', function (req, res) {
res.send('this is home page!');
});
app.use('/base', cookieRouter);
app.listen(1338);
after run app.js, request header has set-cookie value obviously. but can't get it into request header, and req.cookies is empty object {}, even after refreshing the web.
but if i just use simplest demo, it can work, for instance:
router.get('/', function (req, res) {
res.cookie('name', 'test');
});
one more thing, i feel the trouble with express is that only one res.send(), res.redirect()... can be sent as by default it will add head automatically, otherwise, it will come up with error: Can't set headers after they are sent.
someone said add return can solve this problem, but i failed, so want to how how to add, can anyone give an complete demo?
The cookie is missing because the domain attribute is incorrect -- 'localhost:1338' need to be changed to 'localhost'. Port information should not be included in domain.
Yes, according to the Network panel of browser dev tool, there is a Set-Cookie response header (as the screenshot displayed). However, if you check Application - Cookies panel in Chrome (or corresponding panel in other browsers), you will find that: the cookie specified by Set-Cookie header is not there. Browser does not store it and won't send it in the following HTTP requests.
Also, please note that as the cookie's path is /base, only the HTTP requests whose URL starts with /base can send the cookie.

Node Express Middleware how to send the res, req object

I am unable to send the res (request object) between functions. The following code is executed by my app.js (main express middleware):
//app.js calls File.js
//File1.js
var file2 = require('./File2.js);
export.modules = function (req,res,next) {
file2(data) {
res.send(data); //<-- this is not working
}
}
//File2.js
export.modules = function(data){
data = 'test';
}
Also I do not understand when to use next() or when to use res.end().
Its really hard to understand from you code snippets, so i will address your second question regarding next vs send
You use next inside your middlewares, which means you dont want yet to respond to your client with data, but you want to proccess the data from another middleware down the line, when you reach your final middleware you need to use res.send();
note that you cannot use res.send multiple times, so you must call it when you finished your processing and want to respond the data to the user.
you must use middleware with express as following:
var app = express();
app.use(function(req,res, next){
// some proccessing
req.proccessData = "12312312";
next();
})
app.use(function(req,res, next){
// here you respond the data to the client
res.send(req.proccessData);
})
You can also use this with routes(get, post and etc...) Just add next as third param to the route when you want to send data to next stage

Manually injecting express app via `http.createServer` proxy

I am currently authoring a component for a users sites which adds a number of resources to their server. For my part, I am wanting to use express, but the user could be using express themselves or some other web framework.
Because I want this to just work out of the box, I was attempting to setup my express pipeline via proxying http.createServer. Injecting the pipeline this way seems to work reasonably well in cases where I handle the request, but it fails in cases where I let it fall through and execute the users callback (specifically, it says that the response headers have been sent already).
Here is the sample I am working on. Any ideas?
var http = require('http');
var express = require('express');
var setupProxy = function setupProxy() {
var app = buildApp();
var oldCreateServer = http.createServer;
http.createServer = function(callback) {
return oldCreateServer(function(req, res) {n
app.apply(this, arguments);
if (!res.finished) {
callback.apply(this, arguments);
}
});
};
};
var buildApp = function buildApp() {
var app = express();
app.use('/test', function(req, res) {
res.send('Hello World');
});
return app;
};
I suspect your express handling creates a default 404 response when it doesn't match any of your routes. So, that would be the cause of the headers already sent issue when you are not handling it, but trying to pass it on.
So, I think you need your own 404 handler that writes nothing to the request (e.g. does nothing), but keeps Express from handling it.
Or, another possibility would be to call the user's server callback from your express 404 handler and not elsewhere.

Not able to receive empty get request with express static in nodejs

I am trying to fetch web pages using express static and below is the server code.
app.use(express.static('DIR/webfiles'));
app.get('/test', function(req, res) {
console.log("got req");
res.sendfile("login.html");
});
app.get('/', function(req, res) {
console.log("got req");
res.sendfile("login.html");
});
when I request for localhost:port/test (from browser), I am able to see login.html page and it prints "got req" on server end but when I request for localhost:port or localhost:port/ , I am getting some other file in webfiles folder. It does not print "got req". Is empty GET handler overridden by express static?
When I remove "app.use(express.static('DIR/webfiles'));" line, it is able to get empty GET request but doesn't work in way I want it to. Why it is not getting empty request and how to handle empty requests.
Express will process the various route handlers (including the static middleware) in order of declaration.
If you request /, the static middleware will check for a file called webfiles/index.html, and if it exists, it will be returned.
To override this behaviour, make sure that you declare your own route handler before the static middleware declaration:
// This will match requests to `/` and since it's declared before
// the static middleware, it will get to handle those requests.
app.get('/', function(req, res) {
console.log("got req");
res.sendfile("login.html");
});
app.use(express.static('DIR/webfiles'));

Resources