Node JS和Webpack意外的符号<

27

我已开始学习Node JS

这是我的文件。

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');

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

所以,当我访问地址(localhost:3000)并点击app.js时,控制台会报错:

bundle.js:1 Uncaught SyntaxError: Unexpected token <

此外,我的JS文件无法运行。有人能提供修复建议吗?

提前致谢。


请展示 bundle.js 的内容。 - Dmytro Shevchenko
@DmytroShevchenko 完成 - user5471583
<h1>Hello<h1> 需要一个闭合标签。 - Davin Tryon
5个回答

25

您的服务器:

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

…被配置为忽略请求中的所有内容,并始终返回 index.html 的内容。

所以当浏览器请求 /assets/bundle.js 时,它会得到 index.html(并因为那不是 JavaScript 而出现错误)。

您需要注意路径并提供适当的内容,具有适当的内容类型。

这可能最好通过查找一个静态文件服务模块(Google 提供 node-static)来完成 Node(或将 Node 替换为像 Lighttpd 或 Apache HTTPD 这样的东西)。

如果您想同时提供动态内容和静态内容,则 Express 是一个流行的选择(并且支持 静态文件)。


我已经阅读了有关管理静态文件的内容,但没有注意它。现在我会再多读一些相关的内容。谢谢。 - user5471583

6
无论浏览器请求什么,你的服务器都会返回完全相同的文件:index.html
你看到的错误是因为你的 HTML 文件引用了 bundle.js,当请求时,它会返回 index.html 的内容。
你应该使用一个 Web 框架,这样就不必担心这些事情了。例如:Express

没错。在你的 index.html 中删除类似于 <script src="/bundle.js"></script> 的显式定义。它会自动神奇地添加进去。我是通过 Pluralsight 上一些较旧的 React/Redux 教程来到这里的。 - andilabs

5

Express 用户:

告诉 Node 服务器你的静态文件的位置

注意这行代码 >> 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...'))

文档 - https://expressjs.com/zh-cn/starter/static-files.html

祝好运。


0

你需要提供各种静态文件,例如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)

0

只需在您的webpack.config.js文件中添加output: {publicPath: '/',}即可。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接