27

I've started studing Node JS.

So here is my files.

index.html

<!DOCTYPE html>
<html>
<head>
</head>
<body>
  <div id="app">
    <h1>Hello<h1>
  </div>
  <script src='assets/bundle.js'></script>
</body>
</html>

app.js

var http = require("http"),
    path = require('path')
    fs = require("fs"),
    colors = require('colors'),
    port = 3000;

var Server = http.createServer(function(request, response) {
  var filename = path.join(__dirname, 'index.html');

  fs.readFile(filename, function(err, file) {
    if(err) {        
      response.writeHead(500, {"Content-Type": "text/plain"});
      response.write(err + "\n");
      response.end();
      return;
    }

    response.writeHead(200);
    response.write(file);
    response.end();
  });
});

Server.listen(port, function() {
  console.log(('Server is running on http://localhost:'+ port + '...').cyan);

webpack.config.js

module.exports = {
    entry: './src/index.js',
    output: {
        path: __dirname + '/assets',
        filename: 'bundle.js'
    }
}

UPDATE bundle.js

/******/ (function(modules) { // webpackBootstrap
/******/    // The module cache
/******/    var installedModules = {};

/******/    // The require function
/******/    function __webpack_require__(moduleId) {

/******/        // Check if module is in cache
/******/        if(installedModules[moduleId])
/******/            return installedModules[moduleId].exports;

/******/        // Create a new module (and put it into the cache)
/******/        var module = installedModules[moduleId] = {
/******/            exports: {},
/******/            id: moduleId,
/******/            loaded: false
/******/        };

/******/        // Execute the module function
/******/        modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);

/******/        // Flag the module as loaded
/******/        module.loaded = true;

/******/        // Return the exports of the module
/******/        return module.exports;
/******/    }


/******/    // expose the modules object (__webpack_modules__)
/******/    __webpack_require__.m = modules;

/******/    // expose the module cache
/******/    __webpack_require__.c = installedModules;

/******/    // __webpack_public_path__
/******/    __webpack_require__.p = "";

/******/    // Load entry module and return exports
/******/    return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports) {

    alert('Hello');

/***/ }
/******/ ]);

So, when i hit a app.js and visit the address (localhost:3000) i get the error in console.

bundle.js:1 Uncaught SyntaxError: Unexpected token <

Also my JS file doesnt run. Could someone suggest something to fix it?

Thanks in advance

3
  • Show us the contents of bundle.js. Commented Oct 21, 2015 at 13:09
  • @DmytroShevchenko done Commented Oct 21, 2015 at 13:13
  • <h1>Hello<h1> needs a close tag. Commented Oct 21, 2015 at 13:15

5 Answers 5

25

Your server:

var Server = http.createServer(function(request, response) {
  var filename = path.join(__dirname, 'index.html');

… is configured to ignore everything in the request and always return the contents of index.html.

So when the browser requests /assets/bundle.js it is given index.html (and errors because that isn't JavaScript).

You need to pay attention to the path and serve up appropriate content, with the appropriate content type.

This would probably be best done by finding a static file serving module (Google turns up node-static) for Node (or replacing Node with something like Lighttpd or Apache HTTPD).

If you want to serve up dynamic content as well as static content, then Express is a popular choice (and has support for static files).

Sign up to request clarification or add additional context in comments.

1 Comment

I've read about managing static files but didn't pay attention on it. Now i gonna read a bit more about it Thanks
6

No matter what is requested by the browser, your server will always return the same exact file: index.html.

The error you are seeing is because your HTML file has a reference to bundle.js, which, when requested, is returned with the contents of index.html.

You should use a web framework so that you don't have to worry about these things. E.g. Express.

1 Comment

Exactly. Remove yours explicit definition of smth like ` <script src="/bundle.js"></script>` in your index.html. It will be added there anyway automagically. Ended up here following some older tutorial on React/Redux from Pluralsight
5

Express Users :

Let the Node server know the location of your static files

Notice this line >> app.use(express.static('public'))

//server.js
const express = require('express')
const app = express()
// serve static assets from the public folder in project root
app.use(express.static('public')) 
//
app.listen(8080, () => console.log('listening...'))

DOCS - https://expressjs.com/en/starter/static-files.html

Good Luck.

Comments

0

You need to serve all kinds of static files, e.g. https://github.com/expressjs/serve-static#serve-files-with-vanilla-nodejs-http-server

var finalhandler = require('finalhandler')
var http = require('http')
var serveStatic = require('serve-static')

// Serve up public/ftp folder
var serve = serveStatic(__dirname)

// Create server
var server = http.createServer(function(req, res){
  var done = finalhandler(req, res)
  serve(req, res, done)
})

// Listen
server.listen(process.ENV.port || 3000)

Comments

0

Simply add output: {publicPath: '/',} in your webpack.config.js file.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.