【问题标题】:Express and node app returns errorExpress 和节点应用程序返回错误
【发布时间】:2016-10-31 11:32:16
【问题描述】:

我的 react 应用程序有以下 server.js 文件:

var express = require('express');
var path = require('path');
var port = process.env.PORT || 8080;
var app = express();

app.use(express.static('src/client/'));

app.get('*', (req, res) => {
    res.sendFile(path.resolve(__dirname + '/src/client/index.html'))
});

app.listen(port);
console.log('server started');

index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
    <link rel="stylesheet" href="css/foundation.min.css">
    <link href="https://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet">
    <link rel="stylesheet" href="css/font-awesome.min.css">
    <link rel="stylesheet" href="css/style.css">
    <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.6.0/slick.min.css" />
    <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.6.0/slick-theme.min.css" />
  </head>
  <body>
    <div id="app" />
    <script src="bundle.js" type="text/javascript"></script>
  </body>
</html>

当我点击“http://localhost:8080/”时,屏幕是空白的,并且我有一个控制台错误(未捕获的语法错误:意外的令牌 http://localhost:8080/css/style.css”,我可以看到样式表。

【问题讨论】:

  • 您的 index.html 文件可能有问题。
  • 查看更新......
  • 在命令行输入curl http://localhost:8080会有什么结果?
  • 无法连接 localhost:8080 连接被拒绝
  • 尝试打开http://localhost:8080/bundle.js - 可能你想在这里提供 JS 而不是 index.html。您是否在src/client 目录上创建了 bundle.js

标签: node.js express


【解决方案1】:

我更新了以下内容:

来自

app.get('*', (req, res) => {
    res.sendFile(path.resolve(__dirname + '/src/client/index.html'))
});

app.get('/', (req, res) => {
    res.sendFile(path.resolve(__dirname + '/src/client/index.html'))
});

【讨论】:

    【解决方案2】:

    如果你想重定向到其他文件然后这样做,当你像"http://localhost:8080/signup一样调用时会呈现signup.html

    var app   = require('express')();
    app.get('/signup',function(req,res){
    
     res.sendFile(path.join(__dirname+'/src/client/signup.html'));});
    

    如果你想要主页意味着从同一目录获取请求,那么这样做会在这样的请求时呈现"http://localhost:8080/

    var app   = require('express')();
    app.get('/',function(req,res){
    
     res.sendFile(path.join(__dirname+'/src/client/index.html'));});
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-30
      • 2017-04-20
      • 1970-01-01
      • 1970-01-01
      • 2012-08-06
      • 2015-06-17
      • 2019-07-14
      • 1970-01-01
      相关资源
      最近更新 更多