i have a node.js back-end with express sever.
i have routes called templete.rpoutes.js:
const express = require("express");
const templateCtrl = require("../controllers/template.controller");
const router = express.Router();
router.route("/createtemplate").post(templateCtrl.createTemplate);
router.route("/uploadFinalTemplate").post(templateCtrl.uploadFinalTemplate);
// beneath are the routes with issue
router.route("/:templateId/productInfos").get(templateCtrl.productInfos);
router.route("/:templateId").get(templateCtrl.Read);
// router.param("templateId", templateCtrl.templateByID);
module.exports = router;
I have the defined method in template controller where i'm just logging stuff. no backend logic is there yet. so I expect when I make a call to these end point, i should get those logs displayed
I have configured express server as:
app.use("/api/template", templateRoute);
app.use("/api/productInfo", productInfoRoute);
app.use('/api/sendInformation', Notify)
// PORT
const port = process.env.PORT || 5000;
const server = app.listen(port, () => {
console.log("Connected to port " + port);
});
Note: the app is express.router() method and the controllers are required correctly and the other end-points work for the same controller.
so when I send a get request from postman to localhost:5000/api/template/5f870cd3b02fd77d0a576a54 I get a 404 and Not found in my console like this: (Plus the server is running)
as described in the documentation https://expressjs.com/en/guide/routing.html#express-router
const router = express.Router();
router.post("/createtemplate",templateCtrl.createTemplate);
router.post("/uploadFinalTemplate",templateCtrl.uploadFinalTemplate);
router.get("/:templateId/productInfos",templateCtrl.productInfos);
router.get("/:templateId",templateCtrl.Read);
Related
I'm trying to learn nodejs and express and i created a simple server. I want to run some JS code for response.
When I used this method it's works.
const express = require('express');
const path = require('path');
require('dotenv').config();
const app = express();
const port = process.env.PORT || "8000";
app.get('/', (req, res) => {
res.send(`<script>
console.log("Program works!");
</script>`);
});
app.listen(port, () => {
console.log(`Listening to requests on http://localhost:${port}`);
});
But writing JS as String is hard so I tried this:
const express = require('express');
const path = require('path');
require('dotenv').config();
const app = express();
const port = process.env.PORT || "8000";
app.get('/', (req, res) => {
res.send(`<script src="./response.js"></script>`);
});
app.listen(port, () => {
console.log(`Listening to requests on http://localhost:${port}`);
});
And i get this error:
GET http://localhost:8000/response.js net::ERR_ABORTED 404 (Not Found)
When you send this:
<script src="./response.js"></script>
to the browser, the browser will parse that and see the src attribute and will then immediately request ./response.js from your server. But your server doesn't have any route to respond to that request (thus it gets a 404 error back from your server). Remember that a nodejs server serves NO files by default (unlike some other web servers). So, you have to create routes or middleware for anything that you want it to serve.
So, you need to add a route to your server that will response to a request for response.js. First change your <script> tag to this:
<script src="/response.js"></script>
You want the request to be "path absolute" so it does not depend upon the path of the containing page. Then, you need to add a route handler for response.js to your server.
This can be done as a single route:
app.get('/response.js', (req, res) => {
res.sendFile("response.js", {root: __dirname});
});
Or, you can use express.static() to serve a whole directory of publicly available files with one line of code (if you also move all publicly available static files to their own directory away from your server files).
Express app is not working with ger route as postman request get
stuck while fetching reponse for a while. Get route is present
with necessary request parser and app initialisation and setup.
const express = require('express')
const env = require('dotenv')
const cors = require('cors')
const bodyParser = require('body-parser')
//environment variables
env.config();
const app = express();
const PORT = process.env.PORT
app.use(cors)
app.use(bodyParser())
app.get('/', (request, response) => {
response.status(200).send('Hello World');
})
app.post('/data',(req,res,next)=>{
res.status(200).send(req.body)
})
app.listen(PORT,()=>{
console.log("Server is running on", PORT)
})
Express app is not working with ger route as postman request get
stuck while fetching reponse for a while. Get route is present
with necessary request parser and app initialisation and setup.
You should use app.use(cors());
I have checked the code on postman after this change and it is returning response as expected.
Did you try app.use(cors())?
Because I think you are not applying the middleware
For some reason my express router is not processing requests correctly. My router module is in the same directory as the app entry point. The app is located in index.js:
const express = require('express')
const app = express()
// loading router
const mainRouter = require('./mainRoutes.js')
// mounting router
app.use('/', mainRouter)
app.listen(3000)
console.log('Express server running on port 3000')
The router module is located in mainRoutes.js:
const path = require('path')
const express = require('express')
const mainRouter = express.Router()
mainRouter.get('/', function (req, res) {
res.send('Hello World, I\'m Node.js')
})
mainRouter.get('/about', function (req, res) {
res.sendFile(path.join(__dirname, 'views', 'about.html'))
})
module.exports = mainRouter
When I launch the server locally with live-server and make the following example request in chrome browser:
http://127.0.0.1:8080/about
I get the following error response:
Cannot GET /about
Does anyone have any idea as to what the issue is?
The server is listening on port 3000: app.listen(3000)
But you're trying to access it from port 8080: http://127.0.0.1:8080/about
Try http://127.0.0.1:3000/about
I'm been looking around everywhere for the last few days for a way to access my socket IO instance running in Express from my routes and have not found a working solution.
The problem here is that I only run my socket IO instance at run-time and my routes and defined before that obviously.
The most promising solution I have found is one that wraps my routes in a function and requires it in my app.js file with whilst passing in the IO instance as an argument like so var routes = require('routes')(io)
Here is my setup:
app.js
const express = require('express');
const app = express();
const server = require('http').Server(app);
const io = require('socket.io')(server);
io.on('connection', function(client) {
console.log(io.sockets.sockets)
});
app.set('port', 7777);
const routes = require('./routes/index')(io);
app.use('/', routes);
app.listen('7777');
routes.js
module.exports = function(io) {
const express = require('express');
const router = express.Router();
router.get('/test', (req, res) => {
console.log(io.sockets.sockets);
});
return router;
}
If I connect to the WebSocket, my io.on event fires and I get a console log of the connected sockets in the form of a fairly large object that contains the socket id's etc.
If however, I get to the route '/test' I get a console log of a blank object: {}. I would imagine this is because the instance of the socket I am passing down to the routes does not have anyone connected to it at the time hence the blank object is returned, but this is just my best guess.
Where I'm a little stuck is how to get the full instance with all live connections to the route.
Alternatively, I've thought of attaching the io instance to the request object like so in order to have access to it in the routes:
server.on('request', function(req, res){
req.io = io;
}
but couldn't quite get it to work, nor am I sure this is the correct approach.
I imagine this must be a common issue so I would love a clear answer on how to work around this and the correct approach to tackle the issue.
EDIT
So I eventually got my above code working, I hit the '/test' endpoint from an AJAX GET request within the chrome extension instead of my just visiting the URL localhost:7777/test. What I can't understand here is why it works with an AJAX request but not page navigation? (The page navigation is done after I make the socket connection in the extension)
I tried to separate my node routing into two parts: HTML/App and REST. Here is what I've done:
app.js:
var appPort = process.env.PORT || 80;
var express = require('express');
var http = require('http');
var appRouter = require('./routes/index');
var restRouter = require('./routes/rest');
var app = express();
var srv = http.createServer(app);
app.set('port', appPort);
app.set('view engine', 'jade');
app.use(express.static(path.join(__dirname, 'public')));
app.use('/api/rest/', restRouter); // this seems not working .. I never get the expected response
app.use('/', appRouter); // I get this even with localhost/api/rest/...
var server = srv.listen(app.get('port'), function() {
debug('Express server listening ' + server.address().address + ':' + server.address().port);
});
index.js:
var express = require('express');
var router = express.Router();
router.get('/*', function (req, res) {
res.send('HOME')
});
module.exports = router;
rest.js
var express = require('express');
var router = express.Router();
router.get('/api/rest/*', function(req, res) {
res.send('REST API');
});
module.exports = router;
My questions:
1. It's possible in general to build multiple routers in this way?
2. Does the sequence of get.use matter, and/or do I have to deal with 'next'?
3. In case I would like to access a database inside the router can I hand over a parameter like this:
// ...
var client = new pg.Client(dbConnection);
// ...
app.use('/', appRouter(client));
1) It is possible to build multiple routers this way.
Because you are using this:
app.use('/api/rest/', restRouter);
your route calls in rest.js will be relative to /api/rest/ which means your code should be modified in rest.js to look like this:
router.get('*', function(req, res) {
res.send('REST API');
});
I would also encourage you to see the Express multi-router example on GitHub. It illustrates this point very clearly by showing a REST app with versioned routes.
2) The order of things matter
See the Express documentation for app.use and you will note:
Middleware functions are executed sequentially, therefore the order of
middleware inclusion is important.
If you reverse the order of your app.use calls, the router.get('/*', function (req, res) { line in index.js will catch everything before you get to other routes...defeating your purpose.
Also, if you don't call next, Express has no way to know that you are done or even that you want to continue to the next middleware or route.
3) The database question is a modules/scope question
This is more of a scope question than an Express question. I'd suggest looking up some of the excellent writing about javascript scope and also on how Node handles modules.