Webpack proxy messing up my routing? - node.js

So I'm using webpack for a project on 8080 with a backend on 3000. The proxy seems to work fine, as I can send requests to the backend and access it without issue. However. I need to include this middleware that allows me to have a user load the page, and if they've logged in within a certain amount of time, the initial request they send to the server logs them in automatically.
router.use(function (req, res, next) {
//check token for routes beneath vvvv
})
router.post('/preauth', function (req, res) {
//return user account info if req.token is valid
})
When I try to get to prauth, or even any route before that from the page loaded on 8080 I only touch the middleware and nothing else.
When I do npm run build then try it again from the identical page on 3000, it works as expected.
No, CORS is not enabled and the proxy does not rewrite any url.
Does anyone know if something in my Webpack config might be causing this?

You need install Cors in nodejs:npm install cors, you can try the following below or you see: Nodejs + Vuejs
var express = require('express')
var cors = require('cors')
var app = express()
app.use(cors())
app.get('/products/:id', function (req, res, next) {
res.json({msg: 'This is CORS-enabled for all origins!'})
})
app.listen(80, function () {
console.log('This is a CORS-enabled web server listening on port 80')
})

Related

ReactJS Express server side not receive main route

I am using ReactJS with Express JS to develop a website.
I faced a problem when I open the main domain / (https://www.example.com) in the browser, there are no any routes are executed in my server side even app.get("*") not executed and so I can not control the main route redirection.
My server side code:
const express = require('express');
const app = express();
app.use(express.static(path.join(__dirname, 'build')));
app.use(express.json({type: ['application/json', 'text/plain']}))
app.use(cookieParser('secret'));
app.use(session({secret: 'xxxxxxx', cookie: {maxAge: 1576800000000}, resave: true, saveUninitialized: true}));
app.use(passport.initialize());
app.use(passport.session());
// not work
app.get("/", async (req, res) => {
res.status(404).send("");
})
// work for all routes except "/"
app.get("*", async (req, res) => {
res.status(404).send("");
})
const port = 3011;
app.listen(port, () => `Server running on port ${port}`);
OK, what do you expect to see?
Here:
app.get("/", async (req, res) => {
res.status(404).send("");
you tell to send nothing into the browser except code 404. So that's why the page is blank. But it works. To see the result you can open up the developer tools in your browser and check "network" tab - it shows all the responses from the server and you can easily find your 404 answer.
Replace 404 in your code with any other status to see how it works (do not forget to restart server when updates are done).
You can also put something but empty string as send argument, like this:
res.status(404).send('Hello')
As the result you will find "Hello" on the page, and 404 response in developer console tools.
Pay attention that it is not enough just to send 404 status to browser. You are building API, so data can be requested by browsers, applications etc. So you decide how to handle all these options.
For example, you can make a "404.html" page in the root directory and replace you code with this:
app.get('/', (req, res) => {
// respond with html page
res.status(404).sendFile("404.html", { root: __dirname });
})
On that case, custom error page will be sent to the browser.

Why are the middlewares in app.use() not being executed

I am new in nodejs and I just started to play a little with it and middlewares, I looked at some online documentation and did the exact same thing but my middlewares are not being called, I have maximally simplified my problem, so here is the issue:
const express = require('express')
const port = 3000;
const app = express();
app.use( function(req, res, next) {
console.log("Middeware 1 being executed");
next();
})
app.use( function(req, res, next) {
console.log("Middeware 2 being executed");
next();
})
app.listen(port, () => console.log(`Listening on port: ${port}`));
But when I execute this code, in the console I can only see the "Listening on port: 3000" message, why my middlewares are not being executed, this is so weird and I am totally frustrated. Can someone explain what is going on here? Why are they not being executed at all?
Open http://localhost:3000/ in your browser and you will see that logs.
Middleware will be executed by a request from the client.
Middlewares are executed when requests are made. So, if you open a browser and try to open server by http://localhost:3000, you will see your two middlewares being called.
http://expressjs.com/en/guide/using-middleware.html
Good luck.

Protecting post routes NodeJS

I am working on a nodeJS application. So far i've learned you can protect routes with JWT and i've implemented this. The problem is, I am not sure how to protect a route where the user is allowed to post to.
Let's take a register route for example, this route will be used for user registration. I want users to be able to post to this, BUT only from my application. I dont want anyone to just be able to connect to it via postman and post whatever. How do you protect these kind of routes.
Thanks in advance.
You can use CORS middleware to allow only specific clients to access your server https://expressjs.com/en/resources/middleware/cors.html
Example:
var express = require('express')
var cors = require('cors')
var app = express()
var corsOptions = {
origin: 'http://example.com',
}
app.get('/products/:id', cors(corsOptions), function (req, res, next) {
res.json({msg: 'This is CORS-enabled for only example.com.'})
})
app.listen(80, function () {
console.log('CORS-enabled web server listening on port 80')
})

Express CORS not working

I just started my nodejs express template buy cors is not working.
I used npm install cors --save
here is the file:
var express = require('express');
var cors = require('cors');
var app = express();
app.use(cors());
var corsOptions = {
origin: 'https://example.com/',
optionsSuccessStatus: 200
};
app.get('/', cors(corsOptions), function(req, res, next) {
res.json({ message: 'hooray! welcome to our api!' });
});
app.get('/tt', function(req, res, next) {
res.json({ message: 'hooray! welcome to our api!' });
});
var port = process.env.PORT || 3030;
app.listen(port);
console.log('Magic happens on port ' + port);
Now with the above code when I access localhost:3030/tt or / I still see the content and I shouldn't
What's wrong with this.. I just lost like 2 hours working on this.. :(
At this time I would like not to use CORS, but in near future when my app is finished, I want to allow incoming calls only from my project, since this app will be my API.
The behavior you are describing seems is what I would expect.
CORS won't help you filter out incoming calls on the server. In this case the browser's CORS check won't kick-in as it appears you are directly typing in the URL in the browser. Browser does a CORS check only when the the webpage loaded from a particular domain tries to access/submit to a URL in a different domain.
A different way to think about CORS. CORS is intended to protect the user sitting in front of the browser, and not the server-code that is being accessed.

Capture all http requests with node/express

I am looking to capture all of the data from any request (images, fonts, css, js, etc) on my website so that I can capture the file details, specifically the file name and file size. I have found almost an identical question/solution:
Node.js : How to do something on all HTTP requests in Express?
But the solution appears to be deprecated with Express v4. Is there a simple solution to do this? As another approach I have tried the below solution with no luck:
var express = require("express");
var path = require("path");
var port = process.env.PORT || 3000;
var app = express();
var publicPath = path.resolve(__dirname, "public");
app.use(express.static(publicPath));
app.get("/", function(req, res){
// I want to listen to all requests coming from index.html
res.send("index.html");
});
app.all("*", function(){
// can't get requests
})
app.listen(port, function(){
console.log(`server listening on port ${port}`);
});
Also I am not looking to do this from Fiddler/Charles because I am looking to display this data on my site.
Express routes are predicated on order. Notice the answer that you linked in your question has the middleware defined, and used before all other routes.
Secondly you're trying to implement something that requires middleware, not a wildcard route. The pattern in link you provided in your question is not deprecated according to their docs.
app.use(function (req, res, next) {
// do something with the request
req.foo = 'testing'
next(); // MUST call this or the routes will not be hit
});
app.get('/', function(req, res){
if (req.foo === 'testing') {
console.log('works');
}
res.send("index.html");
});

Resources