Not sure how to get express routing to work - express

I have a index.js file with the following code...
const express = require('express');
const app = express();
app.use(express.json({ extended: false }));
app.use('/api/users/', require('./users/routes'));
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server started on PORT ${PORT}`));
and a routes.js file with the following code...
const express = require('express');
const router = express.Router();
router.get('test', (req, res) => {
console.log('im here!')
res.send('hello from test route!');
});
module.exports = router;
my file structure is...
server/
users/
routes.js
index.js
I am able to start the server with no issues, however, if I try to go to the route /api/users/test it does not work and says cannot get that route.
For some reason when I am creating files with the .js extension a .jsx icon comes up. I am using vscode and feel that this might be the issue but I don't know how to fix it?
As an update in my routes file...
router.get('test', (req, res) => {});
needs to change to the following...
router.get('/test', (req, res) => {});
and in my index.js file
app.use('/api/users', require('./users/routes'));
basically, adding the slash before the test and taking away the slash after users.
I do not know why that would be an issue but it now works.

In routes.js:
router
.get ('/test',(req, res) => {
console.log('im here!')
res.send('hello from test route!');
});
You just forgot the slash in front of your route.
You should now see your response # http://localhost:5000/api/users/test.

Related

unable to serve static vuejs files on express

Here is my express code:
const express = require('express');
const serveStatic = require('serve-static');
const path = require('path');
// create the express app
const app = express();
var cors = require('cors');
app.use(cors());
app.use("/",serveStatic ( path.join (__dirname, '/dist') ) );
app.use('/static', express.static(path.join(__dirname, '/dist23')));
app.listen(port, () => {
console.log("listening on "+port)
});
The above code only works for the folder /dist. But when I go to /static, it shows a blank page and this error in the console:
If I put the js files from /dist23 into /dist, then /static works and shows me the application. Its almost like it is looking for files inside /dist and not /dist23. How do I fix it?
Both apps were built using vue-2.6.11. Both directories have files built/bundled for production.
You need to set the content type while serving your static files.
app.get('/index.html', (req, res) => {
res.set('content-type', 'text/plain').sendFile('index.html', { root: path.join(__dirname, 'public/dist/') })
});
app.get('/', (req, res) => {
res.set('content-type', 'text/plain').sendFile('index.html', { root: path.join(__dirname, 'public/dist/') })
});

router.route() doesnt want to work at all

I am trying to run router.route() with the following code
const express = require('express');
const app = express();
const router = express.Router();
router.route('/test').get(function (req, res, next) {
res.send('You have reached localhost:9000/test');
next();
});
app.listen(9000, () => {
console.log('Running on port 9000');
});
But it doesn't seem like anything is happening at all. Regardless of what I do, localhost:9000/test will not return anything Cannot GET /test. I don't understand what I'm doing wrong. Thanks in advance
You have to hook the router into your app with app.use():
const express = require('express');
const app = express();
const router = express.Router();
router.get('/test', function (req, res, next) {
res.send('You have reached localhost:9000/test');
});
app.use(router); // <=== add this
app.listen(9000, () => {
console.log('Running on port 9000');
});
Your original code creates a router object, but that router object is not hooked up to any web server yet. Using app.use(), you can hook it up to your web server so that it actually gets a chance to see the incoming requests.
Also, do not call next() after you call res.send(). Pick one of the other. Once you send a response, you do not want to continue routing to other routes because that will often try to then send another response, but you can only send one response to a given incoming http request.
You can simply use the Router().get(...) function instead.
The <Router>.get('/path', function() {...}); function will listen for incoming traffic to the path /path and then fire the callback function with the parameters request, response and next.
Example:
router.get('/test', function (req, res) {
res.send('You have reached localhost:9000/test');
});
Full example:
const express = require('express');
const app = express();
const router = express.Router();
router.get('/test', function (req, res) {
res.send('You have reached localhost:9000/test');
});
app.listen(9000, () => {
console.log('Running on port 9000');
});
Note: Using the next() function after sending a response to an incoming HTTP request will result in an error.

How to disable CORS on localhost using expressjs

I want to disable CORS on localhost for a specific url, here is my code
const express = require('express')
const app = express()
const port = 3000
app.use(express.static('files'))
app.all('/no-cors/', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "fake");
next();
});
app.get('/', (req, res) => res.send('Hello World!'));
app.get('/sample-json', (req, res) => res.json({"foo": "bar"}));
// it shld show error in console
app.get('/no-cors/sample-json', (req, res) => {
res.json({"cors": "off"});
});
app
.listen(port, () => console.log(Example app listening on port 3000'))
but I open http://localhost:3000/no-cors/sample-json it still show me the json.
Path argument in express().get(path,...) is evaluated as whole string. Path in Express (and URL generally, not only in Express) does not work as folder structure.
That’s why the address /no-cors/sample-json is not catched with your app.all().
If you want it to work, try the path as /no-cors/*

How to use vuejs routing with history fallback and expressjs routes

I've been stuck on this for a number of weeks and I can't figure it out. It's driving me crazy... Ive read numerous tutorials and it sounds like it's something that should work!
I have an expressjs server setup and a vuejs app. I want to be able to serve the vuejs routes with history browser mode and I also want to be able to setup server side routes for my api layer.
If I disable the history mode, everything works ok - but I need to enable history mode, so that I can use auth0 library and callbacks. Callbacks do not allow # in the url.
Here is my code:
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const logger = require('morgan');
const history = require('connect-history-api-fallback');
const app = express();
app.use(require('connect-history-api-fallback')())
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(history({
verbose: true
}));
app.get('/api', (req, res) => res.send('Hello World!'))
app.use('/', express.static(path.join(__dirname, 'dist')));
var port = process.env.PORT || 8080;
app.listen(port);
console.log('server started '+ port);
For the code above, the vuejs app is sitting under /dist and all the routes for that one work. But when I try to hit /api - it is also being redirected to the vuejs app.
Any help would be greatly appreciated! I'm at the point where I'm thinking its just not possible.
I was having the same issue. I fixed it by adding app.use(history()) after my api routes, but before app.use('/', express.static(path.join(__dirname, 'dist')));.
So I think for you it'd be like
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const logger = require('morgan');
const history = require('connect-history-api-fallback');
const app = express();
app.use(logger('dev'));
app.use(bodyParser.json());
app.get('/api', (req, res) => res.send('Hello World!'));
app.use(history({
verbose: true
}));
app.use('/', express.static(path.join(__dirname, 'dist')));
var port = process.env.PORT || 8080;
app.listen(port);
console.log('server started '+ port);
This answer helped me: https://forum.vuejs.org/t/how-to-handle-vue-routes-with-express-ones/23522/2

Mean Stack Root Routing is not working

Can someone help me why default route is not working in my Mean App, But the next routing works
Here when I open http://localhost:3000 I am not able to see any output, But I have defined route in route.js which is working
var express = require('express');
var cors = require('cors');
var bodyparser = require('body-parser');
var mongoose = require('mongoose');
var path = require('path');
const port = 3000;
app.get('/', function (req, res) {
res.send('Test');
console.log('Opened the root path');
});
When I open the page with http://localhost:3000/main I am able to see the Output and also log written in the console
const express = require('express');
const router = express.Router();
router.get('/main', function (req, res, next) {
res.send('This is the Admin Landing Page');
});
router.get('/install', function (req, res, next) {
res.send('This is the Install Landing Page');
console.log('Opened the Install path');
});
module.exports = router;
It looks like you the code you pasted is the full version, and it's not runnable because:
You did not declare app variable.
You did not start the http server.
It's really hard to tell the root cause what's wrong of your code. Following codes works for me:
const express = require('express');
const port = 3000;
let app = express();
app.get('/', function (req, res) {
res.send('Test');
console.log('Opened the root path');
});
let server = require('http').createServer(app);
server.listen(port, function() {
console.log('Server started');
});