How to setup gulp browser-sync for a node / react project that uses dynamic url routing - node.js

I am trying to add BrowserSync to my react.js node project. My problem is that my project manages the url routing, listening port and mongoose connection through the server.js file so obviously when I run a browser-sync task and check the localhost url http://localhost:3000 I get a Cannot GET /.
Is there a way to force browser-sync to use my server.js file? Should I be using a secondary nodemon server or something (and if i do how can the cross-browser syncing work)? I am really lost and all the examples I have seen add more confusion. Help!!
gulp.task('browser-sync', function() {
browserSync({
server: {
baseDir: "./"
},
files: [
'static/**/*.*',
'!static/js/bundle.js'
],
});
});

We had a similar issue that we were able to fix by using proxy-middleware(https://www.npmjs.com/package/proxy-middleware). BrowserSync lets you add middleware so you can process each request. Here is a trimmed down example of what we were doing:
var proxy = require('proxy-middleware');
var url = require('url');
// the base url where to forward the requests
var proxyOptions = url.parse('https://appserver:8080/api');
// Which route browserSync should forward to the gateway
proxyOptions.route = '/api'
// so an ajax request to browserSync http://localhost:3000/api/users would be
// sent via proxy to http://appserver:8080/api/users while letting any requests
// that don't have /api at the beginning of the path fall back to the default behavior.
browserSync({
// other browserSync options
// ....
server: {
middleware: [
// proxy /api requests to api gateway
proxy(proxyOptions)
]
}
});
The cool thing about this is that you can change where the proxy is pointed, so you can test against different environments. One thing to note is that all of our routes start with /api which makes this approach a lot easier. It would be a little more tricky to pick and choose which routes to proxy but hopefully the example above will give you a good starting point.
The other option would be to use CORS, but if you aren't dealing with that in production it may not be worth messing with for your dev environment.

Related

Proxy all requests to server in React using createProxyMiddleware

So on my dev env, I have a React Server on localhost:3000 and a NodeJs server on localhost:5000.
I have used createProxyMiddleware in React to configure the requests. Here is my config:
const {createProxyMiddleware} = require('http-proxy-middleware');
module.exports = function (app) {
app.use(createProxyMiddleware('/auth/google', {target: 'http://localhost:5000'}));
app.use(createProxyMiddleware('/auth/currentUser', {target: 'http://localhost:5000'}));
app.use(createProxyMiddleware('/api/*', {target: 'http://localhost:5000'}));
}
All of these routes work without any problems. For example I have a route like localhost:3000/api/list which gets routed to localhost:5000/api/list.
But now I have a route like localhost:3000/api/list/3132133ffdvf. The random string is some id. This above route does not get proxied. It gives me a 404.
Why is this happening? It shouldn't happen since I have created a proxy for /api/*. Can someone help me out?
The wildcard (*) only matches one directory level. This means that it matches /api/list but not /api/list/id, since the latter has two levels.
Either remove the wildcard, or use a globstar (**):
app.use(createProxyMiddleware('/api', {target: 'http://localhost:5000'}));
or
app.use(createProxyMiddleware('/api/**', {target: 'http://localhost:5000'}));

How can I get create-react-app to use an IP to connect to my api server?

I'm using Facebook's create-react-app. When I start the web-client I see in console:
You can now view web-client in the browser.
Local: http://localhost:3000/
On Your Network: http://192.168.1.107:3000/
The problem is my web-client uses localhost to connect to the api-server, which means I can't use the IP address on different devices to debug issues.
env-variables.js:
export const ENV = process.env.NODE_ENV || 'development';
const ALL_ENV_VARS = {
development: {
GRAPHQL_ENDPOINT_URI: 'http://localhost:4000/graphql',
},
....
I tried updating the above with:
GRAPHQL_ENDPOINT_URI: `http://${process.env.ip}:4000/graphql`,
That did not work, process.env.ip is returning undefined. How can I get the above GRAPHQL_ENDPOINT_URI to use the IP address which somehow create-react-app is getting?
Try adding the following to your client-side package.json:
"proxy": "http://localhost:4000/",
You can then leave the
http://localhost:4000
off of any URLs pointing to the API server from the client side. You would just refer to those addresses as
/graphql/<any additional URL data>
I've performed the same with a Node/Express backend and a React frontend - I resolved the /api portion in my server.js with the following:
//Use our router configuration when we call /api
app.use('/api', router);
just replace /api with /graphql there.
Take a look at this article for further explanation. Hope this helps!
https://medium.freecodecamp.org/how-to-make-create-react-app-work-with-a-node-backend-api-7c5c48acb1b0

Unable to get connect-livereload to work with express server in gulp task

I am working off of Yeoman's gulp-webapp generator. I have modified my gulp serve task to use my Express server, rather than the default connect server it ships with. My issue is with Livereload functionality. I am trying to simply port the connect-livereload to work with my Express server rather than having to install new dependencies. It's to my understanding that most connect middleware should work fine with Express, so I am assuming connect livereload is compatible with Express 4.
Here are the contents of the relevant tasks in my gulpfile:
gulp.task('express', function() {
var serveStatic = require('serve-static');
var app = require('./server/app');
app.use(require('connect-livereload')({port: 35729}))
.use(serveStatic('.tmp'));
app.listen(3000);
});
gulp.task('watch', ['express'], function () {
$.livereload.listen();
// watch for changes
gulp.watch([
'app/*.ejs',
'.tmp/styles/**/*.css',
'app/scripts/**/*.js',
'app/images/**/*'
]).on('change', $.livereload.changed);
gulp.watch('app/styles/**/*.css', ['styles']);
gulp.watch('bower.json', ['wiredep']);
});
gulp.task('styles', function () {
return gulp.src('app/styles/main.css')
.pipe($.autoprefixer({browsers: ['last 1 version']}))
.pipe(gulp.dest('.tmp/styles'));
});
gulp.task('serve', ['express', 'watch'], function () {
require('opn')('http://localhost:3000');
});
With this simple setup, when I run gulp serve in my cmd everything spins up fine and I can accept requests at http://localhost:3000.
Now if I go and change the body's background color from #fafafa to #f00 in main.css and hit save, my gulp output will respond with main.css was reloaded, as seen in the bottom of this screenshot.
However, my webpage does not update. The background color is still light-grey instead of red.
Is there perhaps a conflict between my express server config and the way gulp handles its files? Is my Express server forcing the use of app/styles/main.css rather than the use of .tmp/styles/main.css? Shouldn't the livereload script handle the injection of the new temporary file?
Thanks for any help.
EDIT:
I was able to move forward a bit by adding livereload.js to the script block of my index file, like so:
<script src="http://localhost:35729/livereload.js"></script>
I am now able to get live changes pushed to the client. Why was this file not getting injected before? How can I ensure this is getting used programatically as opposed to pasting it into my files?
I was able to get past this issue by removing the app.use(require('connect-livereload')({port: 35729})) from my gulpfile, along with a couple of other lines, and having that instantiate in my Express server's app.js file.
My gulpfile's express task now looks like this:
gulp.task('express', function() {
var app = require('./server/app');
app.listen(3000);
});
I added in the connect-livereload just above where I specify my static directory in Express:
if (app.get('env') === 'development') {
app.use(require('connect-livereload')());
}
app.use(express.static(path.join(__dirname, '../app')));
Once I started using this setup, I was getting the livereload.js script injected into my document, and client-side changes are now auto-refreshed just how I wanted.
Hope this helps someone!

yeoman 1.0 - make development server accept POST calls

I'm using yeoman for my application which consists of 2 parts - client site with js/html/css and the rest service.
During development I start rest service in Eclipse and start server for my static files with
grunt server
The problem is that I have to do a post request to root url '/' (it's a fake login POST request to make browsers prompt to save passwords).
It worked with yeoman 0.9 but after updating I get:
Cannot POST /
Is there a way to configure grunt server task to accept POST requests?
Thanks!
Leonti
I think you want the connect-rest middleware.
https://github.com/imrefazekas/connect-rest
npm install connect-rest --save-dev
Edit Gruntfile.js, at the top
var restSupport = require('connect-rest');
restSupport.post( { path: '/savequestion'}, function(req, content, next){
next(null, {result: 'OK'});
});
In your connect or livereload middleware section:
livereload: {
options: {
middleware: function (connect) {
return [
lrSnippet,
mountFolder(connect, '.tmp'),
mountFolder(connect, yeomanConfig.app),
restSupport.rester( {'context': '/forms'} ),
rewriteRulesSnippet, // RewriteRules support
The key part is "restSupport.rester()", remove the context if you don't want it.
This simple function should just reply with the json object {result: 'OK'} to everything you post to /forms/savequestion . It should at least let you build out scaffolding in grunt server :9000 mode before you have build your templates. Without this you would have to $.get() each $.post() and then change it during or after the build.

basic node website returns "Cannot GET /" when hosted with forever.js

I'm trying to get my first production node website up (just a basic hello world on my production web server).
The below is what I'm using (basic http proxy to pass off apache websites to port :9000 and node websites to port :8000). I know this part works because apache vhosts are forwarded as I expect. What does not work however is the node part -instead I get the error below
"Cannot GET /"
This is running node 0.8.1 on Ubuntu 12.04
I'm hosting this with forever.js (forever start foo.js). when I echo the NODE_ENV -it shows "production"
It might also be noted that I don't have node_modules on the path (as you will see in my require statements) **not sure if this has anything to do with my issue
var httpProxy = require('/usr/local/lib/node_modules/http-proxy/lib/node-http-proxy');
var express = require('/usr/local/lib/node_modules/express/lib/express');
httpProxy.createServer(function (req, res, proxy) {
var nodeVhosts = ['www.mysite.com'];
var host = req.headers['host'];
var port = nodeVhosts.indexOf(host) > -1
? 8000
: 9000;
proxy.proxyRequest(req, res, {host: 'localhost', port: port});
}).listen(80);
var one = express.createServer();
one.get('/', function(req, res){
res.send('Hello from app one!')
});
var app = express.createServer();
app.use(express.vhost('localhost', one));
app.listen(8000);
Since you are running Ubuntu, you might take a look at upstart. In case you don't know, upstart replaces the old-school-unix init-scripts approach to starting and stopping services. (Those were dark, scary days!) If you want your app to start automatically when your box boots/reboots and restart automatically after it (your app) crashes, then you want upstart. Learning the basics of upstart is easy, and then you have a tool that you can use over and over again, whether it's node, apache, nginx, postfix, mongodb, mysql, whatever!
I mean no disrespect to the good folks who work on the forever module. Arguably, it does have a solid use case, but too often it is used to imperfectly duplicate the bedrock which is already on your system -- upstart. Also, you might Google for some of the comments made by experienced users and some node.js committers about the forkability of node.js and the pitfalls, which are very relevant to forever.
I'd like to post links, but I don't have enough rep yet. Hopefully what I wrote is enough to google on.
Good luck!
http-proxy module doesn't change the host header of the request, and that's what connect/express vhost uses to distinguish virtualhosts.
In this line:
proxy.proxyRequest(req, res, {host: 'localhost', port: port});
you tell the proxy server to proxy the unchanged request to localhost:port.
So what you need to do is to change:
var app = express.createServer();
app.use(express.vhost('localhost', one));
app.listen(8000);
to:
var app = express.createServer();
app.use(express.vhost('www.mysite.com', one));
app.listen(8000);
and it should work.
Alternatively you can simply set the req.headers.host to localhost before proxying.

Resources