How to disable CORS on localhost using expressjs - express

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/*

Related

BodyParser causes all API requests to hang. Even basic GET requests

As the title says, I simply don't understand what is going on here. Once I include the app.use(bodyParser.json) line, Postman just keeps handing on any request I make. I lost a good portion of the day thinking I messed up my routes.
I narrowed it down to it in this little testing file:
const express = require("express")
const bodyParser = require("body-parser")
const env = require("dotenv");
const app = express()
env.config();
app.use(bodyParser.json);
app.get("/", (req, res) => {
res.status(200).json({
message:"Hello World"
})
});
app.post("/data", (req, res) => {
req.status(200).json({
message: req.body
})
});
app.listen(process.env.PORT, ()=>{
console.log(`Server listening at port ${process.env.PORT}`);
})
Can anyone tell me what is happening and how I can fix it?
You need to call JSON body parser as a function (with brackets):
app.use(bodyParser.json());
There is another bug in the post method "data", You should call status from "res" object:
app.post("/data", (req, res) => {
res.status(200).json({
message: req.body
})
});

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.

express order difference make result different

const express = require('express')
const app = express();
app.use('/users', (req, res, next) =>{
res.send('Hello from express Again.')
});
app.use('/', (req, res, next) =>{
res.send('Hello from express.')
});
app.listen(4000, function () {
console.log('console server listening on 4000');
})
when i go to to http://localhost:4000/users it will render: Hello from express Again..
BUT if I change the code order like:
app.use('/', (req, res, next) =>{
res.send('Hello from express.')
});
app.use('/users', (req, res, next) =>{
res.send('Hello from express Again.')
});
Now I do it again: http://localhost:4000/users The result is Hello from express.
I guess it's configuration issue. But I just don't know which configuration.
Yes, the order you declare your routes in Express is important. Routes are matched from first to last in order of declaration and the first route that matches gets the request. If it sends a response and doesn't call next(), then the following routes do not get a chance to run.
Also relevant here is that app.use(somePath, ...) will match any route that starts with somePath. So, this:
app.use('/', (req, res, next) =>{
res.send('Hello from express.')
});
will match every single possible route because they all start with "/".
So, when you do this:
app.use('/', (req, res, next) =>{
res.send('Hello from express.')
});
app.use('/users', (req, res, next) =>{
res.send('Hello from express Again.')
});
And, send a request for /users, then the first route will match everything and thus the second route is never called.
Whereas, when do this:
app.use('/users', (req, res, next) =>{
res.send('Hello from express Again.')
});
app.use('/', (req, res, next) =>{
res.send('Hello from express.')
});
The /users route gets the first chance to match so when you send a request for /users, that /users route gets matched first and takes the request.
Note: You should only be using app.use() when you either want to match all possible http verbs or you WANT the greedy partial match that is in play here. If you don't want one of those, then use the verb-specific version such as app.get(). In your example, if you make both of these app.get(), then it is no longer order-sensitive because app.get() only matches complete path matches and does not do partial matches.
Both of these work the same:
app.get('/', (req, res, next) =>{
res.send('Hello from express.')
});
app.get('/users', (req, res, next) =>{
res.send('Hello from express Again.')
});
and:
app.get('/users', (req, res, next) =>{
res.send('Hello from express Again.')
});
app.get('/', (req, res, next) =>{
res.send('Hello from express.')
});
Because only one of them will match / and only one will match /users.

Not sure how to get express routing to work

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.

Middleware gets hit way too many times while next.js is compiling

Iam using next.js and express.js . if I use a middleware (server.use(req, res, next)) it gets hit dozen times while the page is compiling, which makes my app crash completly ...
const express = require('express')
const next = require('next')
const port = parseInt(process.env.PORT, 10) || 3000
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()
console.log('page loaded')
app.prepare().then(() => {
const server = express()
server.use((req, res, next) => {
console.log('ping')
next();
})
server.get('/', (req, res) => {
return app.render(req, res, '/index', req.query)
})
server.get('*', (req, res) => {
return handle(req, res)
})
server.listen(port, err => {
if (err) throw err
console.log(`> Ready on http://localhost:${port}`)
})
})
If I try to load the page, it prints
ping
ping
ping
ping
ping
ping
ping
ping
ping
ping
ping
ping
ping
ping
ping
of course if I put a real middleware here it makes everything crash ...
I wish for the middleware to run only if the page is actually requesting something ... So only once per 'real user' request
I had the similar trouble, but only on client-side. In my case there were a lot of parasitic requests (trackers, internal API, fonts, some _next_static things). They triggered the middleware and it was the reason of ERR_TOO_MANY_REDIRECTS.
So, as for me, filtering parasitic requests and redirects helped to solve the problem:
if (new RegExp(/^.*(fonts|_next|vk.com|favicon).*$/).test(request.url)) {
return NextResponse.next()
}