I couldnt find answer for this question.So that..for example
app.js
//express require
app.get("/test",function(req,res) {
res.send("hello world");
});
app.listen(3000)
when we work it via "node app.js".. We see "hello world" we requested http://ip:3000/test on browser .
but when we changed file, for example
//express require
app.get("/test",function(req,res) {
res.send("hello world 2");
});
app.listen(3000);
when we refreshed to browser.. we still see "hello world"...because we does not "node app.js command"
well!! but why????
when we worked "node app.js" command on console..what does node work for this?
Actually node doesn't refreshes the content until you restart the server. So, just restart the server after changing the content.
You can use --watch to watch for the changes automatically restart the server if content is changed.
Related
Until now, I have been using create-react-app for my projects, with the express-server and the react client each in their own folders.
However, I am now trying to avoid create-react-app in order to really understand how everything work under the hood. I am reading an Hacker Noon article that explains how to setup react with typescript and webpack. In this article they also have the express server at the root of the client which compiles everything itself:
const path = require('path'),
express = require('express'),
webpack = require('webpack'),
webpackConfig = require('./webpack.config.js'),
app = express(),
port = process.env.PORT || 3000;
app.listen(port, () => { console.log(`App is listening on port ${port}`) });
app.get('/', (req, res) => {
res.sendFile(path.resolve(__dirname, 'dist', 'index.html'));
});
let compiler = webpack(webpackConfig);
app.use(require('webpack-dev-middleware')(compiler, {
noInfo: true, publicPath: webpackConfig.output.publicPath, stats: { colors: true }
}));
app.use(require('webpack-hot-middleware')(compiler));
app.use(express.static(path.resolve(__dirname, 'dist')));
In the end, the start command looks like it:
"start": "npm run build && node server.js"
So I assume the client and the server start on the same port.
Why would you do such a thing? Are there any pros and cons?
It is true that this will allow your development to happen using the same server as express and that web pack will continuously update your dist/index.html file with whatever updates you make to your file. There's not too much of a disadvantage to this as this is just for development. But typically on prod you'll have a single built file that you will serve. And it will not web pack-dev-middleware to be running. Once you've built your server. For the purposes of production it might be possible that you'll only need static assets. But typically, even the server which serves mostly client files will potentially need a server if you want to do server side rendering and/or code splitting.
The command: "npm run build && node server.js" will run the bash/cmd commands into the terminal. npm run build is one step because of the use of && it will if that command succeeds, run the next command which is node server.js which is a strange command I would probably run node ./ (and put the server as index.js) or at least just write node server.
What I'd prefer to see in your package.json:
"start": "yarn build && node ./"
That would be possible if you mv server.js index.js (and npm i -g yarn).
Another thing to note, and look into is what the build step does.
Further Explanation:
The command runs the build step so check what your "build": key runs in your package.json.
This command will probably not exit with the code 1 (any exit code of a terminal process that is above 0 will result in an error and will not pass the &&).
Presumably, the build process described in the package.json will take all the javascript and CSS files and put them into the index.html file which will then be sent to the client side whenever someone access the '/' path.
After that succeeds, it will start the server that you put the code to above.
res.sendFile(path.resolve(__dirname, 'dist', 'index.html'));
will happen if anybody comes across the '/' path.
This could be really rookie. I want to know if there is a way that I can configure nodemon to refresh the same tab instead of opening a new tab each time I make a change in my js files.
nodemon is not able to do that. What you are looking for is something like browser-sync or LiveReload.js.
I use a package called reload. Assuming you are doing this on your FE and that you already installed express.js and nodemon
first install reload
npm install --save-dev reload
Than create a index.js file or server.js or whatever name your want
this is my index.js:
const express = require('express')
const http = require('http')
const reload = require('reload')
const opn = require('opn')
const app = express()
app.engine('html', require('ejs').renderFile)
app.set('view engine', 'html')
app.set('src', './src')
app.use(express.static('src'))
app.get('/', (req, res) => res.render('index'))
const server = http.createServer(app)
server.listen(8080, function() {
console.log('Listening to port 8080...')
})
opn('http://localhost:8080')
reload(app)
the opn package can be intalled with
npm install opn
it will automatically open your localhost once you type npm start on your terminal
on HTML you have to insert something like this after the closing body tag:
</body>
<script src="/reload/reload.js"></script>
and on package.json the following:
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "nodemon index.js -e els,js,html,css,json"
},
The only problem with this is that it will reopen the browser every time you make a change to those files and well as reload the current opened one sure to the opn package. I am still going to create a function to prevent that, eventually. Hope that helps!
Its Simple.
To run your server use
npm start
instead of
nodemon server
Just run npm start nodemon server.
It works for me. Make sure you have latest nodemon version installed.
I've started a new app with create-react-app, and ejected from that. I made a small express server as follows:
const express = require('express');
const app = express();
if(process.env.NODE_ENV === 'production') {
app.use(express.static('build'));
}
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`Server started at: http://localhost:${port}/`);
});
In package.json I've added a line, "proxy": http://localhost:3000", as well as switching the commands:
"scripts": {
"run": "npm-run-all -p watch-css start-js",
"start": "node server.js",
},
run used to be start.
However now of course when I run npm start and go to localhost:3000, I get Cannot GET /. I need this server to receive and return local API calls I'll be making from my app, but I also want it to run a hot-reloading dev server just like the old npm start (now npm run) command did. How do I do this?
Some time ago I made a fork of the create-react-app repository adding webpack watch option because of this same reason. It might help you.
Just to add more info, I really invested time looking on how to get webpackdevserver to build the "bundle.js", and found that it is not possible because it loads the bundle into memory but doesn't persist it, so the file is never created. The only way available is the webpack watch option but, I don't understand why the create-react-app team can't add it to the repo, it's a really requested feature, and there are more forks than mine that solves this issue. So, you have three options:
Use the proxy server in package.json (if it works)
Make your own fork and add the watch option, or use an existing one
Don't use create-react-app
When I refresh page on index route (/) and login page (/login), it works fine.
However, my website gets error as I refresh on other routes, for example /user/123456.
Because no matter what the request is, the browser always gets HTML file.
Thus, both of the content in main.css and main.js are HTML, and the browser error.
I have already read the README of create-react-app.
Whether I use serve package ($serve -s build -p 80) or express, it will produce the strange bug.
Following is my server code:
//server.js
const express = require('express');
const path = require('path');
app.use(express.static(path.join(__dirname, 'build')));
app.get('/*', (req, res) => {
res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
const PORT = process.env.PORT || 80;
app.listen(PORT, () => {
console.log(`Production Express server running at localhost:${PORT}`);
});
Edit: I have figured out where caused the problem.
I created a new project, and compared it to mine. The path of static files in the new project is absolute, but in my project is relative.
As a result, I delete "homepage": "." in the package.json.
//package.json
{ ....
dependencies:{....},
....,
- "homepage": "."
}
Everything works as expected now. How am I careless...
I have figured out where caused the problem.
I created a new project, and compared it to mine. The path of static files in the new project is absolute, but in my project is relative.
As a result, I delete "homepage": "." in the package.json.
//package.json
{ ....
dependencies:{....},
....,
- "homepage": "."
}
Everything works as expected now. How am I careless...
If your route /user/** is defined after app.get('/*', ... it might not match because /* gets all the requests and returns you index.html.
Try without the * or declare the other routes before.
First, I thought you misunderstood the server part. In your case, you use serve as your server. This is a static server provided by [serve]. If you want to use your own server.js, you should run node server.js or node server.
I also did the same things with you and have no this issue. The followings are what I did:
create-react-app my-app
npm run build
sudo serve -s build -p 80 (sudo for port under 1024)
And I got the results:
/user/321
I guessed you might forget to build the script. You can try the followings:
remove build/ folder
run npm run build again
Advise: If you want to focus on front-end, you can just use [serve]. It will be easy for you to focus on what you need.
I have been trying and failing to get basic breakpoints working in a fresh sails js app.
I create a new sails project called test and added a couple lines of code so I could hit a route and try to initiate a breakpoint in my terminal:
// app/controllers/TestController.js
module.exports = {
test: function (req, res) {
console.log('test');
debugger;
return res.json({
text: 'hello',
});
}
}
in my routes file:
// /config/routes.js
'get /test': 'TestController.test',
then I go to my terminal and use nodemon to launch the sails server with:
$ nodemon debug -w . app.js
My one caveat is that this solution should work with something like nodemon, forever, or supervisor that will allow for livereload on the nodeserver