javascript - Heroku 找不到我的 index.js 文件

标签 javascript node.js heroku webpack

我在heroku中遇到此错误GET https://my-app.herokuapp.com/index.js 404(未找到)

我的 Procfile 中有这样的内容:web: npm start

然后在我的 package.json 中我有 "start": "node ./app/index.js"

根级别的我的应用程序文件夹包含一个 index.js,其中包含:

var express = require('express');
var app = express();

app.use('/', express.static('public'));

app.get('/', function(req, res) {
    res.sendFile(__dirname + '/index.html');
});

app.listen(process.env.PORT || 8080);

我的 webpack.config.js 文件包含:

var path = require('path');
const webpack = require('webpack')

module.exports = {
 entry: './main.js',

 output: {
   path: path.resolve(__dirname, 'public'),
   filename: 'index.js'
 },

 module: {
   loaders: [
     {
       test: /\.js$/,
       exclude: /node_modules/,
       loader: 'babel',
       query: {
         presets: ['es2015', 'react', 'stage-2']
       }
     },
     {
        test: /\.scss$/,
        loaders: ["style-loader", "css-loader", "sass-loader"]
      }
   ]
 }
}

也许我需要将其指向我的 public/index.js 文件,但当我这样做时,它仍然无法识别它。

有什么想法吗?

最佳答案

这是对 Node 和/或服务器一般工作方式的误解。您应该能够访问 GET https://my-app.herokuapp.com/,它会返回您公共(public)目录中的 index.html 文件文件夹。告诉 Node 以 "start": "node ./app/index.js" 启动只是意味着运行此文件来启动服务器。服务器然后监听您定义的路由:

app.get('/', function(req, res) {
    res.sendFile(__dirname + '/index.html');
});

这是在路径 https://my-app.herokuapp.com/

上监听

如果您想收听https://my-app.herokuapp.com/anotherroute,您可以将之前的内容更改为:

app.get('/anotherroute', function(req, res) {
    res.sendFile(__dirname + '/index.html');
});

由于您使用了 app.use('/',express.static('public')); 任何与您的路线匹配的文件都会自动提供。这意味着如果您的 public 目录中有一个文件,例如 apple.jpg,您可以使用 https://my-app.herokuapp.com/apple 检索它.jpg

关于javascript - Heroku 找不到我的 index.js 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42830357/

相关文章:

spring-boot - 使用 H2 DB 将 Spring Boot 部署到 Heroku

javascript - 通过数据表 jquery 插件添加的按钮上的 jQuery 单击事件

javascript - 删除 beforeunload 的事件监听器

javascript - 运行 socket.io 和express-nodejs 设置时出错

javascript - 这是一个好的服务器负载平衡系统吗?

Heroku - DNS 简单配置

javascript - 动态坐标谷歌地图无法加载

javascript - 通过选择单选按钮启动和停止 AJAX

node.js - Node js -如何从数组中删除特定的_id数据

heroku - 为什么我的 heroku 应用程序不使用安全连接