Cannot Get Express Route to Activate on Localhost - node.js

The Problem
I have a server (node.js) on localhost port 8080, with the client running on 3000. In order to run my web app, I run both concurrently, but only use the server as a proxy for the client to bypass CORS requests - it does not serve any static pages. I have found that although making API calls from client code to the server works perfectly fine (or a script that makes unirest requests), I cannot test simple routes on the browser on localhost:8080/[route], such as this one:
app.get('/login', (req, res) => {
console.log('serving login');
res.send('login');
})
//on the Google Chrome browser: localhost:8080/login
The Question
The /login route never gets triggered. Is my URL incorrect on the browser? If so, how can I correct it?
Side Note
This may/may not change anything, but I am using React Router HashHistory for my client side. Interestingly when I type in localhost:8080/login into the browser, it automatically converts to localhost:8080/login#/.

Related

Https createServer, load cookie and load clients index.html

I am trying to setup a login system on a website.
In order to do that, I have to load http only cookies.
In order to load them, I have to send them back to the client via the response object in the createServer function when https starts up.
I have successfully done that via here:
setting up https cookie in nodejs
The problem is twofold.
The https server cookie only loads if I include the port number in the url.
How do I get it to load without including the port number?
When the server kicks in and loads the cookie, the static index.html that was always supposed to load on the client, doesn't load and instead all i get is what was written into the response object on the server. How do I get to load the cookie, and just load that static html file?
I have tried sending in the entire html file as a respnose from the server side. But I'm not sure about that, plus i get MIME type problems in the browser.
I am not sure for the first part but for 2nd one,
you have to properly mention about response data type in response header.
so your should be something like this one:
var app = express(); app.get('/test', function(req, res) { res.sendFile('views/test.html', {root:__dirname}) });
For your first part of the question "How do I get it to load without including the port number?" You can try creating virtual host e.g for localhost:3000 will be something.xyz.
And for your second part you need to serve index.html with render method as follow
server.get('/', function (req, res) {
res.render('index', { greeting: 'Welcome' });
});
Where index is you static file inside view directory.
I've created a small demo, that might get you on the right track:
https://github.com/bergur/simple-server-with-websocket
This example includes:
https web server
websocket server
logic to get the cookies
serving a temp.html file without express
example of javascript class
example of dependency injection in nodejs

React + Express With Passport.js

I am setting up a full-stack application using React and Express JS.
I'm using Passport.js for authentication and have come across a slight problem...
So my front-end and back-end are two separate packages running on two different ports. On my express app, I have created a route like the following.
app.post('/api/account/login', (req, res, next) => {
passport.authenticate('local', {
successRedirect: '/dashboard',
failureRedirect: '/users/login',
}) (req, res, next);
});
This is pretty standard as far as Passport.js goes. Basically, if it authenticates the credentials I have provided, then it should redirect me to /dashboard. If not, then to the other mentioned route.
I am able to call reach this endpoint from my react application and get the correct response like the following in the network tab of chrome.
Request URL: http://localhost:3000/dashboard
Request Method: GET
Status Code: 304 Not Modified
Remote Address: 127.0.0.1:3000
Referrer Policy: no-referrer-when-downgrade
However, it doesn't actually redirect me to /dashboard. Is it not possible to do it this way?
Thanks.
It sounds like your React app is calling the route via ajax using something like fetch.
The way you're using Passport assumes that a browser is issuing the requests directly. On a successful login, Passport returns a Redirect response (HTTP 302 or similar), which the browser honors and redirects the user to.
Ajax requests don't work this way, since there isn't any navigation happening.
You'll need to handle this yourself on the React side of things. Your Express app will need to handle the session authentication by (for instance) returning a JSON message with a token or storing a session cookie. You'll need to update your React app to recognize this and then navigate to the correct route via client-side Javascript.
If you're using react-router, they have some sample code that might be helpful.

Create React App with Express API cookie authentication

My setup is thus:
Node server running Express which runs an API.
Inside a subdirectory client is a Create React App project, with the proxy field set to the URL of the Express API.
I start both processes and access the CRA in my browser, which sends requests to the Express API through the proxy.
This all works fine.
In production, I will build the CRA and serve it from the Express app, like so:
app.use('/api/:controller', (req, res, next) => {
return router(req, res, next)
})
app.get('*', (req, res) => {
res.sendFile(path.join(`${__dirname}/client/build/index.html`));
})
My only roadblock is how to handle authentication. I could quite easily do an onload fetch request back to the API when the React app is initialised in the browser to see if the user has a session, but it seems like a waste.
In development (and I guess production for that matter), what would be a good way to 1) read the cookie from the incoming request and 2) pass on the currentUser object to the index.html above (in production) or to CRA in development.
To clarify, I was wondering if there are any specific CRA recipes for handling authentication from the server, before it sends the response back to the browser? (in this dual-purpose codebase setup)
Exact issue: In development, because I'm running yarn run cra, it's spinning up it's own webpack dev server, which serves the React app. So I don't believe I can really get at the request before it gets sent back to the browser.

create-react-app with Express

I need to query a database and I'm using create-react-app. The library to connect to the DB (pg-promise) does not work with Webpack and needs to be running on a Node server.
So I installed Express and have this:
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, '..', 'build', 'index.html'));
})
How can I load data from the database from the React pages? I though of using request but how can I make a request to my own server? And what should I add to the lines of code above? I think it would be something like:
app.get('/query/:querybody', (req, res) => {
// process and return query
})
Is this right? How can I make it work with a SPA?
Probably the most friction-free method would be to have a separate app.js or server.js along side your CRA application. You can use a tool like concurrently to run both your React app and the express app.
The trick is to serve your express app on a different port than the default :8080 that CRA serves on. Usually 8081 is a good choice, as it's a common convention to use port numbers that are close together when developing.
In your React app, you will need to make sure you use the full URL for the express endpoint: http://localhost:8081/query/...
On the server side you are going in the correct direction: you need to setup endpoint which will respond with data based on request. In you example you setup an endpoint for a GET HTTP request. If you will need to pass a complex request (for example add new record to database), consider using POST HTTP requests.
On the client side (in the browser) you will need a library that will assist you in sending requests to your server. I can recommend to try Axios (https://github.com/mzabriskie/axios). Usually if you omit protocol, server name and port, request will be sent to the server from which the page was loaded:
http:127.0.0.1:8001/api/endpoint => /api/endpoint

Use Node.js as workaround for Cors

Using Nodejs and Express 4, I am trying to do a post on
my express server which in turn will take inputs from browser
and do a post on external server as a CORS workaround.
This the route to my server:
app.post('/api', api.postme);
This is my api.js file.
exports.postme = function (req, res, next) {
res.send("hello Apis");
};
For Example an external server:
https://website/NoJSONPHere/
params: page=1, query="frogs"
Is it possible to do this??
Use a second node server, host it somewhere in the cloud.
Then have mobile (blocked) app make calls against your server.
So,
your app> your server > their server.
Avoids,
your app > their server.
The reason this works is server to server connections or not blocked.
Browser to server is sometimes blocked.

Resources