【问题标题】:How to send headers in Express [MEAN]如何在 Express 中发送标头 [MEAN]
【发布时间】:2020-02-03 20:28:15
【问题描述】:

我是 Express 的初学者。所以我可能没有正确地提出问题。我创建了一个 MEAN 应用程序,其中我将frontendbackened 分开。前端在port:4200 上运行,服务器在port:3000 上运行。作为部署的一部分,我想在同一个端口上运行前端和后端。我收到 MIME 类型错误,有人告诉我我的服务器环境有问题。也许我没有正确发送标题。这是我的代码: 我在代码本身中提到了尝试过的解决方案<----TRIED THIS

server.js

const express = require('express');
express.static.mime.define({'application/javascript': ['js']}); <----TRIED THIS

const bodyParser = require('body-parser');
const path = require('path');

// express.static.mime.define({'application/javascript': ['js']}); <----TRIED THIS

const api = require('./routes/api');

const PORT = 3000;
const app = express();

app.use(express.static(path.join(__dirname, 'dist')));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

app.use('/api', api);

app.get('/', function(req, res) {

  // res.send('Hello from the server'); <----TRIED THIS
  // res.writeHead(200, {'Content-Type': 'text/html'}); <----TRIED THIS
  // res.set('Content-Type', 'text/plain'); <----TRIED THIS
  // res.setHeader("Content-Type","application/json"); <----TRIED THIS

  res.sendFile(path.join(__dirname, 'dist/application/index.html'));
})
app.listen(PORT, function() {
  console.log('Server listening on PORT '+PORT);
});

api.js 例如,我只向您展示 GET 函数

const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const db = <my db string>;
const jwt = require('jsonwebtoken');

mongoose.connect(
 ...
)

function verifyToken(req, res, next) {
 ...
}

router.get('/myarticles', (req, res) => {
  var person="Tanzeel Mirza";
  console.log('Get request for tanzeel articles');
  Article.find({contributor: person}, (error, article) => {
    if(error) {
      console.log(error)
    }
    else {
      if(!article) {
        res.status(401).send('Invalid email')
      }
      else if(2>4) {
        console.log("test passed");
      }
      else {
        res.json(article);
      }
    }
  })
})

module.exports = router;

但我还是得到了

由于不允许的 MIME 类型(“text/html”),从“http://localhost:3000/runtime-xxx.js”加载模块被阻止。

由于不允许的 MIME 类型(“text/html”),从“http://localhost:3000/polyfills-xxx.js”加载模块被阻止。

由于不允许的 MIME 类型(“text/html”),从“http://localhost:3000/main-xxx.js”加载模块被阻止。

请纠正我。

PS:我针对 MIME 错误here 提出了单独的问题。但没有答案。

【问题讨论】:

  • JavaScript 文件是否保存在静态文件夹 path.join(__dirname, 'dist') 中?如果是这样,记录从path.join 返回的值并检查它是否正确。如果不是,哪个中间件调用应该处理服务脚本文件?
  • @Tanzeel。静态中间件应自行处理 mime 类型。请查看repl repl.it/repls/SoreFearlessNagware。我做了一些小的修改,它似乎对我有用
  • @nithin。谢谢你,先生。这与路径的微小变化有关。先生,您能否将其发布为答案,以便我接受。真的很感谢楼主
  • @nithin 你能确认你不是在请求URL中以dist/开头的js文件吗?这将返回一个 404 http 状态消息 mimetype text/html 并且还可以解释问题!
  • @traktor53 URL 中没有 {dist/}

标签: javascript deployment mean-stack mime-types


【解决方案1】:

由于您的资产位于 dist/application 文件夹中,请使用 app.use(express.static(path.join(__dirname, 'dist/application')));

要匹配所有 Web 应用程序路由,请使用 app.get('*', function(req, res) { res.sendFile(path.join(__dirname, 'dist/application/index.html')); })

这是一个通用路由,只有在 express 找不到任何其他路由并始终提供 index.html 时才会被调用。例如,任何有效的/api 路由永远不会到达这个处理程序,因为有一个特定的路由来处理它。

server.js 的最终代码

const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');


const api = require('./routes/api');

const PORT = 3000;
const app = express();

app.use(express.static(path.join(__dirname, 'dist/application')));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

app.use('/api', api);

app.get('*', function(req, res) {
  res.sendFile(path.join(__dirname, 'dist/application/index.html'));
})

app.listen(PORT, function() {
  console.log('Server listening on PORT '+PORT);
});

注意几点。

要提供静态文件,您无需手动设置任何标题。 Express 在您使用express.static 中间件功能设置为静态目录的文件夹(在您的情况下为dist 文件夹)中查找文件。 Express 还会根据文件扩展名设置响应头。

所以您的代码中不再需要express.static.mime.define

在您的情况下,您定义了app.use(express.static(path.join(__dirname, 'dist')));,它在dist 文件夹中侦听静态文件。在这个app.use 命令中,您没有使用挂载路径,这意味着所有请求都将通过静态中间件。如果中间件在 dist 文件夹中找到具有相同名称、路径和扩展名的资产,则返回该文件,否则将请求传递给其他路由处理程序。

另外,如果您使用的是静态中间件,只要 dist 文件夹(dist 文件夹的直接子文件夹)中有 index.html,您的“/”路由处理程序将永远不会被调用,因为响应将由中间件。

如果您在 dist 文件夹(dist 的直接子文件夹)中没有 index html 文件,但它存在于 dist 的子文件夹中的某个位置,并且您仍然需要使用根路径“/”来访问它,那么您只需要路径“/”的路由处理程序,如下所示。

app.get("/", function(req, res) {
  res.sendFile(path.join(__dirname, "dist/application/index.html"));
});

dist/application/index.html 中使用"./" 引用的JS 文件相对于dist 文件夹本身和 dist/application 文件夹。

您可以参考此 REPL 以获取更新的代码?。 https://repl.it/repls/SoreFearlessNagware

试试下面的网址

/api/myarticles - 由“/api”路由处理程序渲染

/api/myarticles.js - 由静态资产中间件渲染,因为文件存在于 dist/api 文件夹中

/ - 使用“/”路由处理程序和 res.sendFile 渲染,因为 dist 文件夹中不存在 index.html。

/test.js - 使用静态中间件渲染,因为文件存在于 dist 文件夹中

其他参考链接。

https://expressjs.com/en/api.html#res.sendFile

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

【讨论】:

  • 不幸的是,更新后的代码让我陷入了同样的老问题。请参阅此stackoverflow.com/questions/57978442/…。已经18天了,还是没有答案。
  • @Tanzeel 在我生成您的资产之后。使用了另一个问题中提供的 github 链接。我能够加载应用程序。只有一个变化 app.use(express.static(path.join(__dirname, 'dist/application')));所有资产都在应用程序文件夹中。所以 express 静态中间件应该指向那里。
  • 是的,先生。我也这样做了。为我工作。但是尝试刷新页面。然后你会遇到问题。我是说。单击导航栏上的某个按钮,然后单击浏览器上的刷新按钮。
  • 这里是github上的整个项目github.com/tmtanzeel/social-coder。在ng build --prod 之前。请填写。
  • 将 app.get('/', function(req, res) {}) 更改为 app.get("*", function(req, res) {})。并重启
【解决方案2】:

1. 使用ng build cmd 在服务器文件夹内部或外部构建您的 Angular 项目。

2.要在服务器中构建您的项目,请更改angular-cli 中的dist-文件夹路径。

3.要更改路径,请使用cli cmd或编辑angular-cli.json文件的"outDir": "./location/toYour/dist" 或者通过使用这个 cli cmd ng build --output-path=dist/example/

4.然后在您的服务器根文件中使用 express 包含静态build/dist 文件夹。

5.点赞app.use(express.static(path.join( 'your path to static folder')));

6.现在重新启动您的服务器。

【讨论】:

    猜你喜欢
    • 2019-05-12
    • 1970-01-01
    • 2015-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-19
    • 2020-06-04
    相关资源
    最近更新 更多