Expressjs static javascript file not loading - javascript

I'm setting up express server with create-react-app.
AT console I'm getting
Uncaught SyntaxError: Unexpected token < bundle.js:1
When I click on error it shows me homepage html.
While using morgan logger its giving me 200 ok.
GET /static/js/bundle.js 304 1.145 ms - -
Also when i view source click on css link it shows me css while click on javascript link it shows me blank page(homepage html).
Here is the the server code.
var express = require('express');
var bodyParser = require('body-parser');
var logger = require('morgan');
var path = require ('path');
var data = {};
express()
.use(logger('dev'))
.use(express.static(path.join(__dirname, 'flashcard-app/build')))
.use(bodyParser.json())
.get('/api/test', (req, res) => res.json("Great news every thing is working fine."))
.get('/api/data', (req, res) => res.json(data))
.post('/api/data', (req, res) => res.json(data = req.body))
.get('*', function(req, res) {
console.log('serving path:', path.join(__dirname+'/flashcard-app/build/index.html'));
res.sendFile(path.join(__dirname, 'flashcard-app/build/index.html'));
})
.listen(3333, function(){
console.log('server running at 3333');
});
Also this is custom server.js file not one that provided by express-generator. I'm running by node server_old.js instead of using ./bin/www
Help comment tips appreciated.

You are trying to fetch /static/js/bundle.js, but there is no bundle.js in static/js.
I think you are trying to use index.html that tries to bundle.js while your webpack config builds main.[hash].js

Related

How can i get response from another JavaScript file while working with nodejs and express?

I'm trying to learn nodejs and express and i created a simple server. I want to run some JS code for response.
When I used this method it's works.
const express = require('express');
const path = require('path');
require('dotenv').config();
const app = express();
const port = process.env.PORT || "8000";
app.get('/', (req, res) => {
res.send(`<script>
console.log("Program works!");
</script>`);
});
app.listen(port, () => {
console.log(`Listening to requests on http://localhost:${port}`);
});
But writing JS as String is hard so I tried this:
const express = require('express');
const path = require('path');
require('dotenv').config();
const app = express();
const port = process.env.PORT || "8000";
app.get('/', (req, res) => {
res.send(`<script src="./response.js"></script>`);
});
app.listen(port, () => {
console.log(`Listening to requests on http://localhost:${port}`);
});
And i get this error:
GET http://localhost:8000/response.js net::ERR_ABORTED 404 (Not Found)
When you send this:
<script src="./response.js"></script>
to the browser, the browser will parse that and see the src attribute and will then immediately request ./response.js from your server. But your server doesn't have any route to respond to that request (thus it gets a 404 error back from your server). Remember that a nodejs server serves NO files by default (unlike some other web servers). So, you have to create routes or middleware for anything that you want it to serve.
So, you need to add a route to your server that will response to a request for response.js. First change your <script> tag to this:
<script src="/response.js"></script>
You want the request to be "path absolute" so it does not depend upon the path of the containing page. Then, you need to add a route handler for response.js to your server.
This can be done as a single route:
app.get('/response.js', (req, res) => {
res.sendFile("response.js", {root: __dirname});
});
Or, you can use express.static() to serve a whole directory of publicly available files with one line of code (if you also move all publicly available static files to their own directory away from your server files).

Express / Node sendFile weird behavior

I'm trying to combine Node/Express and serve React files but its not working as desired.
server.js (my own REST API)
var express = require('express')
var app = express()
var public = __dirname + "/../frontend/build";
app.use(express.static(public));
app.get('/', (req, res) => {
res.sendFile(public + "/index.html");
});
app.get('/api/g', (req, res) => {
res.send("Test")
})
app.listen(3001);
My React build is in the public variable location.
Now when I go to localhost:3001 where my node server runs, I get this page
Page
but the issue is when I go to localhost:3001/api/g I still get the same page. Meaning, I dont get my "res.send" part, I have no idea why this is happening. Can anyone familiar with Node/Express help me out?

express send file error 404 not found

I have the following code server side code:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendfile('index.html');
});
app.get('/data/cursor.png', function(res, res) {
res.type('png');
res.sendfile('data/cursor.png');
});
and on the client side i have the following code:
<img class="cursor" src="data/cursor.png">
and when i load the index.html i get the following error:
GET http://localhost:3000/cursor.png 404 (Not Found)
why is this happening? i also send some other files like the javascript file and css. and they work just fine...
so res.sendfile('js/drawingV2.js'); works totally fine.
app.get('/js/drawingV2.js', function(res, res) {
res.sendfile('js/drawingV2.js');
});
could someone explain to me what i am doing wrong?
if you need more code or if i am unclear pls let me know :)
You are only sending your user the index.html file, or that's how Express is seeing it. You need to send the entire directory with all the files to the user, which is what express.static does.
Let's assume you have a directory, public, that has index.html in it, and a folder called data, with cursor.png in it.
server.js
public -
index.html
data -
cursor.png
And then -
var express = require('express');
var app = express()
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.use(express.static("public")) // serve the whole directory
And viola! It should work. (express.static serves an entire directory)

Node, Angular Error: ENOENT: no such file or directory

I have been following the a scotch.io tutorial to create my first node and angular app. I have seen that relative paths are a common issue online for the Error: ENOENT: no such file or directory which as far as I can tell is the same as the tutorial so I'm why its not working.
The full error message is:
Error: ENOENT: no such file or directory, stat'/Users/badman/githubRepos/travelGuide/app/public/index.html'
at Error (native)
My folder structure is here.
My server.js:
// set up web server
var express = require('express');
var app = express();
var bodyParser = require("body-parser");
// routes
require('./app/routes.js')(app);
// listen (start app with node server.js)
app.listen(3000, function() {
console.log("server going");
})
routes.js:
module.exports = function (app) {
app.get('*', function (req, res) {
res.sendFile(__dirname + '/public/index.html'); // load the single view file (angular will handle the page changes on the front-end)
});
};
Any help is appreciated :)
I had the same problem and I moved
app.get('*', function (req, res) {
res.sendFile(__dirname + '/public/index.html'); // load the single view file (angular will handle the page changes on the front-end)
});
to server.js right under the require('./app/routes.js')(app); and that fixed it! Because it was looking for index.html in the wrong place when a server-side route was being called. I think you could have also changed the path too but I found this to be clearer.

How do I serve a static file using Node Express?

I was having trouble settings up a very basic static file sever using express with Node.js. I set up a simple server.js but cannot see any files when I load the URL localhost:9000 in my web browser.
All I see is a page saying: Cannot get /
var express = require('express');
var app = express();
app.use(function(req, res, next) {
next();
});
app.use(express.static(__dirname));
app.listen(9000);
Simply you're exposing nothing. Do you have, for example, an index.html file? Try this:
app.get("/", function(req, res) {
res.sendfile("index.html");
});
Did you go through the NodeSchool workshoppers? They have step-by-step examples that cover this and more.
Here is the workshop for Express.
Here is my solution for the 'static' question in the workshop.
var express = require('express')
var app = express()
app.use(express.static(process.argv[3]||path.join(__dirname, 'public')));
app.use(require('stylus').middleware(__dirname + '/public'));
app.post('/form', function(req, res) {
res.writeHead(200, { 'Content-Type': 'text/plain' })
res.end()
})
app.listen(process.argv[2])
Express does not create a directory listing. Even thought it does not list the files in the directory, it does serve them up when hitting them in the web browser.
Point the browser to the actual file:
http://localhost:9000/public/test.html
Originally I found this confusing because I had expected the express server to list directories; when seeing "something"... a page that said "Cannot get /" I assumed that page would normally have a list of files.

Categories

Resources