Node Express Router can't get response params - node.js

I can not retrieve route parameters with a simple express.Router() in an web app.
Here is a minimal example:
var http = require('http');
const express = require('express');
const app = express();
app.use('/hello/:world', express.Router()
.get('/', function (req, res) {
console.log("hello : ", req.params); //
res.status(200).send({status: 'success', params: req.params});
}));
var port = process.env.PORT || 3000;
app.set('port', port);
var server = http.createServer(app);
server.listen(port);
I don't get any error, the res.params is simply empty when I try to reach:
http://localhost:3000/hello/100 for example.
Here is the response:
{
"status": "success",
"params": {}
}
What I have tried so far is to set express.Router({ params: 'inherit' })
as told here: https://github.com/expressjs/express/issues/2151#issuecomment-44716623 but it doesn't change anything.
And here is the manual: http://expressjs.com/en/guide/routing.html

Answer:
The thing that finally worked for me, based on these:
API doc :http://expressjs.com/en/api.html
SO example: Express Router undefined params with router.use when split across files
is to set express.Router({mergeParams: true}).
So:
var http = require('http');
const express = require('express');
const app = express();
app.use('/hello/:world', express.Router({mergeParams: true})
.get('/', function (req, res) {
console.log("hello : ", req.params); //
res.status(200).send({status: 'success', params: req.params});
}));
var port = process.env.PORT || 3000;
app.set('port', port);
var server = http.createServer(app);
server.listen(port);
Is giving the following response over http://localhost:3000/hello/10
{
"status": "success",
"params": {
"world": "10"
}
}

Related

Issue to add socketio to API Express

i'm trying to add socket.io on my already existing NodeJS API REST Project.
var express = require('express')
var bodyParser = require('body-parser');
var https = require('https');
var http = require('http');
var fs = require('fs');
var router = require('./route/router');
require('dotenv').config();
var app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(require('helmet')());
app.use(function (req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Authorization,Content-Type');
next();
});
router(app);
if (process.env.PRODUCTION === "false") {
http.createServer(app).listen(8080, function() {
console.log('8080 ok');
});
var io = require('socket.io')(http);
} else {
const options = {
cert: fs.readFileSync('./../../etc/letsencrypt/live/test.com/fullchain.pem'),
key: fs.readFileSync('./../../etc/letsencrypt/live/test.com/privkey.pem')
};
https.createServer(options, app).listen(8443, function() {
console.log('8443 ok');
});
var io = require('socket.io')(https);
}
io.sockets.on('connection', socket => {
console.log('socketio connected');
});
I have no error displayed (server side). But, when I tried on client side, this.socket = io('ws://localhost:8080/');, it's not working at all.
I get GEThttp://localhost:8080/socket.io/?EIO=3&transport=polling&t=NG6_U6i [HTTP/1.1 404 Not Found 1ms] browser console.
It seems that something is not ok with the server, but I can't find what's going on
Any idea ?
Thanks
Try this way, you need to include (I don't know if this is the correct word to use) the express server into the socket.io server.
const express = require('express');
const socketio = require('socket.io');
const port = process.env.PORT || 3006;
const app = express();
const server = app.listen(port, () => {
console.log(`App started on port ${port}`)
});
const io = socketio(server, { forceNew: true });
io.on('connect', (socket) => {
// do this
// do that
});
The code above is a skeleton of how express and socket.io are used together. Please modify it as per your needs.
Good luck.

What am I doing incorrectly with my https request?

I'm learning how to build a RESTful api with Node and Express, and I am having an issue with this https request. I am trying to make a GET request to Scryfall's api (documentation here: https://scryfall.com/docs/api), but whenever I run my server and check the browser I get a message stating
"localhost didn’t send any data. ERR_EMPTY_RESPONSE".
As I'm new to using Node and Express, I'm not really sure what I am doing wrong. Here is the code for my server.js and app.js files.
//server.js
const https = require('https');
const app = require('./backend/app');
const port = process.env.PORT || '3000';
app.set('port', port);
const server = https.createServer(app); //pass the express app to the server
server.listen(port);
and
//app.js
const express = require('express');
const app = express();
app.use((req, res, next) => {
console.log('This is the first middleware');
next();
});
app.get('https://api.scryfall.com/cards/named?fuzzy=aust+com', (req, res, next) => {
res.send('${res.body.name} is the name of the card!');
});
module.exports = app;
Any help would be greatly appreciated! Thanks in advance!
👨‍🏫 For an example, you can do it with this code below 👇:
const express = require('express');
const axios = require('axios');
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use((req, res, next) => {
console.log('This is the first middleware');
next();
});
app.get('/', async (req, res, next) => {
try {
const result = await axios.get('https://api.scryfall.com/cards/named?fuzzy=aust+com');
res.status(200).send(result.data);
}catch(ex) {
console.log(ex.message);
}
});
app.listen(3000, () => {
console.log('Server is up');
})
💡 From the code above, you can call the endpoint: localhost:3000 and than you will get the result.
I hope it's can help you 🙏.
You can easily make a get request like this.
const express = require('express');
const app = express();
const port = 8080;
const bodyParser = require('body-parser');
//Expect a JSON body
app.use(bodyParser.json({
limit: '50mb' //Request size - 50MB
}));
app.get('/test', (req, res, next) => {
// do whatever you need here
res.status(200).send("ok");
});
app.listen(port, function () {
console.log(`Server is running.Point your browser to: http://localhost:${port}`)
});

Express route returning 404 error

The express route in my node app is returning a 404 error. It works locally but on the production server it returns a 404 error (bear in mind that I changed the AJAX url to the one on my production server before uploading). My code:
server.js:
const path = require('path');
const http = require('http');
const express = require('express');
const publicPath = path.join(__dirname, '/../public');
const port = process.env.PORT || 8080;
var app = express();
var server = http.createServer(app);
app.use(express.static(publicPath));
app.post('/active-screens', function(req, res) {
res.send('route works!');
});
server.listen(port, () => {
console.log(`Server is up on port ${port}`);
});
index.js:
function checkRoute(){
$.ajax({
url: "http://localhost:8080/active-screens",
type: "POST"
})
.success(function(data){
console.log(data);
});
}
checkRoute();
It was a CORS issue as pointed out by #WejdDAGHFOUS.
I updated my server.js to this:
const path = require('path');
const http = require('http');
const express = require('express');
const cors = require('cors');
const publicPath = path.join(__dirname, '/../public');
const port = process.env.PORT || 8080;
var app = express();
var server = http.createServer(app);
app.use(express.static(publicPath));
app.post('/active-screens', cors(), function(req, res) {
res.send('route works!');
});
server.listen(port, () => {
console.log(`Server is up on port ${port}`);
});

Unable to post on nodejs in heroku

I have a nodejs app running on Heroku. Here is the server.js file
var express = require('express')
, cors = require('cors')
, app = express();
var http = require('http').Server(app);
var io = require("socket.io").listen(http);
app.use(cors());
require('./modules/routes.js')(app,io);
app.set('port', process.env.PORT || 5000);
app.listen(app.get('port'), function () {
console.log('Express server listening on port ' + app.get('port'));
});
Here is my routes.js
"use strict";
const bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var time = require('express-timestamp');
var Promise = require('promise');
var momentjs = require('moment');
var _ = require('lodash');
var method = routes.prototype;
function routes(app, io) {
app.use(time.init);
app.use(cookieParser());
app.use(session({ secret: 'asdo8rter65edfgfd53wet34634632y4bluaq', resave: true, saveUninitialized: true }));
app.all('/', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
next();
});
app.use(bodyParser.json());
app.post('/testHeroku', function(req, res) {
console.log(req);
res.write(JSON.stringify({
process: "success"
}));
res.end();
});
}
method.getroutes = function() {
return this;
}
module.exports = routes;
I'm trying to access /testHeroku from an ionic app running in android emulator.
Ionic code:
vm.testHeroku = function(){
console.log('testing heroku');
var testdata = {
url: config.baseURL + 'testHeroku',
dataServer: {
serverTaskRequest: 'getUADSF'
}
}
runajax.runajax_function(testdata, function (testdataResponse) {
if (testdataResponse.process == 'success') {
alert(testdataResponse.process);
}
});
};
Here goes my config.baseURL = abcd-1234.herokuapp.com (This is example for the heroku app url)
I don't receive any return form the http call.
Code for run_ajax service
.service('runajax', ['$http', function ($http) {
this.runajax_function = function (request, callback) {
var url = request.url;
var dataServer = request.dataServer;
// console.log('runajax function called -> ' + url);
// console.log(dataServer);
$http.post(url, dataServer).success(function (data, status, headers, config) {
callback(data);
})
.error(function () {
callback(status);
});
}
}])
I got it working. There was an error with app.set('port', process.env.PORT || 5000); I changed it to var port = process.env.PORT || 8080;

Not able to solve Express Middleware issue

My first piece of code below:
var express = require('express');
var app = express.createServer(express.logger());
app.get('/', function(request, response){
response.send('Hello World 2');
});
var port = process.env.PORT || 5000;
app.listen(port, function(){
console.log("Listening on " + port);
});
Threw up the error: "Most middleware (like logger) is no longer bundled with Express and must be installed separately"
So I looked at StackOverflow, did npm install morgan, and changed my code to:
var express = require('express');
var logger = require('morgan');
var app = express.createServer(logger());
app.get('/', function(request, response){
response.send('Hello World 2');
});
var port = process.env.PORT || 5000;
app.listen(port, function(){
console.log("Listening on " + port);
});
Now I get this error:
var app = express.createServer(logger());
^
TypeError: Object function createApplication() {
var app = function(req, res, next) {
app.handle(req, res, next);
};
mixin(app, proto);
mixin(app, EventEmitter.prototype);
app.request = { __proto__: req, app: app };
app.response = { __proto__: res, app: app };
app.init();
return app;
} has no method 'createServer'
That is because createServer method has been removed from express.
use
app = express();
app.use(logger())
instead of
app = express.createServer(logger())
Many things got changed from express 3.0 to 4.0. You should have a look here
You should create app with express(). Afterwards, you can setup any middleware (like morgan in this case) with app.use:
var express = require('express');
var logger = require('morgan');
var app = express();
app.use(logger());
...
app.use() documentation: http://expressjs.com/4x/api.html#app.use. (Linking to Express 4.x documentation as not explicit what Express version you're running).
There is an exact same example like the one I wrote above in Morgan's README in GitHub.

Resources