I just started to study nodejs and express, and was trying to make a simple router. In the beginning it worked, if I remember correctly, but since I reopened the project it hasn't worked anymore.
var express = require('express');
var app = express();
var route = express.Router();
route.get('/',(req,res)=>{
res.send('Something');
})
app.get('/post',route);
app.listen(3000);
When I make a GET to 127.0.0.1:3000/post I expect "Something" in my response body, instead I get the default node 404.
The problem is that the path is not "cut", in fact it works if I use route.get('/post',...;
from what I have seen in many examples, and from the documentation itself, when a router is invoked, the path is "cut", am I wrong?
For now I have tried to reinstall express, thanks in advance for your answers. I searched around and couldn't find any other similar problems.
It's because you didn't register the middleware (use is a way to register middleware) and you don't need two endpoints ('/'). your code runs perfectly now:
var express = require('express');
var app = express();
var route = express.Router();
route.get('/post',(req,res)=>{
res.send('Something');
})
app.use(route);
app.listen(3000);
As jfriend00 pointed out to me in the comments, the mistake is to use .METHOD() to invoke the route, rather than .use() .
Related
I have a custom domain set up in Heroku which works fine.
I can access my site using both my app name and custom domain.
I can access a route using my standard Heroku URL, but not using the custom domain.
For example:
Works:
https://{myappname}.herokuapp.com
https://{myappname}.herokuapp.com/callback
https://{customdomain}.com
Does not work:
https://{customdomain}.com/callback
Server config:
const express = require("express");
const path = require("path");;
const callback = require("./callback");
const app = express();
// Body parser middleware
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// Serve static assets if in production
if (process.env.NODE_ENV === "production") {
app.use("/callback", callback);
// Set static folder
app.use(express.static("client/build"));
app.get("*", (req, res) => {
res.sendFile(path.resolve(__dirname, "client", "build", "index.html"));
});
}
// Init server/port
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Server running on port ${port}`));
I know its too late but I am writing for those who face this issue in the future.
I was also facing this issue and solved through this.
Was Not Working
https://{customdomain}.com/callback
This Worked for me.
https://www.{customdomain}.com/callback
I figured this out, it was pretty simple and I feel stupid, however I will answer this here in case anyone ever has the same issue.
Problem:
I had a React route/component called Callback. This React component was calling a Node.js route also called Callback, which processes information then redirects to a new React route/component.
Simple fix was to change my React route/component to callbackPage, leaving my Node.js route as Callback.
So in summary, I had a webpage URL with the same name as a server API route. when I visited this page, instead of the page being rendered, the API route was run and basically did nothing and timed out. I'm still confused as to why it worked with my app URL but not my custom domain.
I'm fairly new to nodeJS/Express which I'm learning at the moment.
There seems to be different methods of creating a http server and I'm wondering what the difference is. E.g.....
From a socket.io tutorial:
var app = require('express')();
var http = require('http').Server(app);
...and from a nodejs tutorial:
var express = require('express'),
app = express.createServer();
Can someone explain the difference between the two, particularly in regards to the first example? I'm presuming the empty brackets after the express require is an anonymous function, but what is that performing? Why pass the app to the Server method?
I am pretty new to node.js and now I am doing a project on building a website on node.js. Sorry if my question is very naive.
I am using express framework.
My app.js is listening at port (3000).
In my route.js, I got some data from calling some API. I want to display the data to my datapoint.jade file. And because I want to draw those datapoint I have to embed a javascript file in jade. I want to use socket.io to achieve this sending and receiving data.
However, all the examples to construct socket is in app.js. I get data in router.js(in one of its callback function). app.js require router.js.
How can I send data from route.js to app.js and then send out to client side.
Could you please guide me some related and useful information? Or my design would not work at all?
A common paradigm is to pass any dependencies to your child modules:
// app.js
var socket = require('socket.io');
var app = require('express')();
var routes = require('./routes.js')(app, socket);
app.listen();
// routes.js
module.exports = function(app, socket){
var routes = {};
app.use('/', routes.handleIndex)
socket.on('connection', function(){
...
})
}
I'm working on a project which consists in creating a game of the goose like. In order to do that, I'm using Node.js, Express, jade and now Socket.io. But I encounter some trouble, like, in example, to share the position of one client to the other client. Because my variable position is in a function in index.js and I don't know how I can use Socket.io in a route file. I try some things, but nothing works.
On internet, I've seen some people who say that there is no-sense to use Socket.io in an express route file. So how can I do that ?
In my index.js I've that :
exports.deplacement = function(io)
{
return function(req,res)
{
//[...]
io.sockets.on('connection', function(socket)
{
socket.broadcast.emit('position', space);
});
res.render('moteur' //[...]);
}
}
And in my moteur.jade I've done this :
script(src="/socket.io/socket.io.js")
script.
var socket = io.connect('http://localhost:3000');
socket.on('position ', function(space) {
alert(space);
})
First of all, I'm not sure what your question exactly means, but if it is what I think it is then I think what you mean by using socket.io in a route file is to be able to include the client side javascript lib provided with socket.io module of Node.
In order to do that, you have to allow the socket.io module to listen to server. This works like a middle-ware itself. Everything has to go through socket.io first before they are routed to the server. So, when you request the client side lib, it is uploaded to the client.
var express = require('express')
, routes = require('./routes')
, http = require('http');
var app = express();
var server = app.listen(3000);
var io = require('socket.io').listen(server)
Please be gentle with me. I'm new to async coding and have been thrown headfirst into an intensive project using node to develop and API server. I'm loving it but some things aren't coming naturally.
Our project is built using express js. We have a file, server.js where we instantiate an express server which in turn instantiates our router and so on. I need to integration test this now (partially) complete server. Normally what I do is from the command line run '%node server.js' and then using either python requests or curl make requests and check the responses.
Now I've been tasked with writing a unit and integration test suite so that we can automate our testing going forward. I've been using mocha and now am trying to use supertest for the integration testing. The problem is that supertest expects a server object which it then applies tests to however our file that builds our server object doesn't return anything. I don't want to modify that file so I am stumped as to how to access the server object to use for testing.
My server file looks (in part) like this:
var express = require('express')
var app = express();
// Express Configuration
app.use(express.favicon()); //handles favicon request, which keeps it out of the log when using a browser :)
app.use(express.bodyParser()); //slurps up the body in chunks the node.js way :)
// ...and so on
and my mocha test file looks like this
var request = require('supertest')
, app = require('../server.js')
, assert = require("assert");
describe('POST /', function(){
it('should fail bad img_uri', function(done){
request(app)
.post('/')
.send({
'img_uri' : 'foobar'
})
.expect(500)
.end(function(err, res){
console.dir(err)
console.dir(res)
done();
})
})
})
when I run this test I get a complaint about the app object not having a method named address. My question is, is there a way I can require/call the server.js file so that the app object will be in scope? Or am I going about this wrong. I also played around a little bit with using http.js to make calls directly to the server but didn't have luck that way either. Thanks!
You need to export the app object in server.js:
var app = express();
module.exports = app;
...