如何在 Express [MEAN] 中发送 headers
How to send headers in Express [MEAN]
我是 Express 的初学者。所以我可能没有正确地提出问题。我创建了一个 MEAN 应用程序,其中我将 frontend
和 backened
分开了。 port:4200
的前端 运行 和 port:3000
的服务器 运行。作为部署的一部分,我想 运行 前端和后端都在同一个端口上。我收到 MIME 类型错误,有人告诉我我的服务器环境有问题。也许我没有正确发送 headers。这是我的代码:
我在代码本身中提到了尝试过的解决方案 <----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;
但我还是得到了
Loading module from “http://localhost:3000/runtime-xxx.js” was blocked because of a disallowed MIME type (“text/html”).
Loading module from “http://localhost:3000/polyfills-xxx.js” was blocked because of a disallowed MIME type (“text/html”).
Loading module from “http://localhost:3000/main-xxx.js” was blocked because of a disallowed MIME type (“text/html”).
请指正。
PS:我针对 MIME 错误 here 提出了单独的问题。但没有答案。
由于您的资产位于 dist/application 文件夹中,请使用 app.use(express.static(path.join(__dirname, 'dist/application')));
要匹配所有网络应用程序路由,请使用 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);
});
有几点不对
要提供静态文件,您无需手动设置任何 headers。 Express 在您使用 express.static
中间件功能设置为静态目录的文件夹(在您的案例中为 dist
文件夹)中查找文件。 Express 还根据文件扩展名设置响应 headers。
因此您的代码中不再需要 express.static.mime.define
。
在您的情况下,您定义了 app.use(express.static(path.join(__dirname, 'dist')));
,它在 dist
文件夹中侦听静态文件。在此 app.use
命令中,您没有使用挂载路径,这意味着所有请求都将通过静态中间件。如果中间件在 dist 文件夹中找到具有相同名称、路径和扩展名的资产,它 returns 文件,否则请求将传递给其他路由处理程序。
此外,如果您使用的是静态中间件,只要 dist 文件夹中有 index.html(dist 文件夹的直接 child),您的“/”路由处理程序将永远不会得到被调用,因为响应将由中间件提供。
如果您在 dist 文件夹中没有索引 html 文件(dist 的直接 child),但它存在于 dist 的子文件夹中的某处,您仍然需要使用根路径“/”,只有这样你才需要路径“/”的路由处理程序,如下所示。
app.get("/", function(req, res) {
res.sendFile(path.join(__dirname, "dist/application/index.html"));
});
在 dist/application/index.html
中使用 "./"
引用的 JS 文件是相对于 dist 文件夹本身和 NOT dist/application
文件夹引用的。
您可以参考此 REPL 以获取更新的代码。
https://repl.it/repls/SoreFearlessNagware
试试下面的网址
/api/myarticles
- 由“/api”路由处理程序呈现
/api/myarticles.js
- 由静态资产中间件呈现,因为文件存在于 dist/api 文件夹中
/
- 使用“/”路由处理程序和 res.sendFile 呈现,因为 index.html 在 dist 文件夹中不存在。
/test.js
- 使用静态中间件呈现,因为文件存在于 dist 文件夹中
附加链接供参考。
1.Build 您的 angular 项目,使用 ng build
cmd 在服务器文件夹内部或外部。
2.To 在服务器中构建项目,更改 angular-cli
中的 dist
文件夹路径。
3.To 更改路径,使用 cli cmd 或编辑 angular-cli.json
文件的 "outDir": "./location/toYour/dist"
或者通过使用此 cli cmd ng build --output-path=dist/example/
4.Then 在您的服务器根文件中使用 express 包含静态 build/dist
文件夹。
5.Like这个app.use(express.static(path.join( 'your path to static folder')));
6.Now 重启你的服务器。
我是 Express 的初学者。所以我可能没有正确地提出问题。我创建了一个 MEAN 应用程序,其中我将 frontend
和 backened
分开了。 port:4200
的前端 运行 和 port:3000
的服务器 运行。作为部署的一部分,我想 运行 前端和后端都在同一个端口上。我收到 MIME 类型错误,有人告诉我我的服务器环境有问题。也许我没有正确发送 headers。这是我的代码:
我在代码本身中提到了尝试过的解决方案 <----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;
但我还是得到了
Loading module from “http://localhost:3000/runtime-xxx.js” was blocked because of a disallowed MIME type (“text/html”).
Loading module from “http://localhost:3000/polyfills-xxx.js” was blocked because of a disallowed MIME type (“text/html”).
Loading module from “http://localhost:3000/main-xxx.js” was blocked because of a disallowed MIME type (“text/html”).
请指正。
PS:我针对 MIME 错误 here 提出了单独的问题。但没有答案。
由于您的资产位于 dist/application 文件夹中,请使用 app.use(express.static(path.join(__dirname, 'dist/application')));
要匹配所有网络应用程序路由,请使用 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);
});
有几点不对
要提供静态文件,您无需手动设置任何 headers。 Express 在您使用 express.static
中间件功能设置为静态目录的文件夹(在您的案例中为 dist
文件夹)中查找文件。 Express 还根据文件扩展名设置响应 headers。
因此您的代码中不再需要 express.static.mime.define
。
在您的情况下,您定义了 app.use(express.static(path.join(__dirname, 'dist')));
,它在 dist
文件夹中侦听静态文件。在此 app.use
命令中,您没有使用挂载路径,这意味着所有请求都将通过静态中间件。如果中间件在 dist 文件夹中找到具有相同名称、路径和扩展名的资产,它 returns 文件,否则请求将传递给其他路由处理程序。
此外,如果您使用的是静态中间件,只要 dist 文件夹中有 index.html(dist 文件夹的直接 child),您的“/”路由处理程序将永远不会得到被调用,因为响应将由中间件提供。
如果您在 dist 文件夹中没有索引 html 文件(dist 的直接 child),但它存在于 dist 的子文件夹中的某处,您仍然需要使用根路径“/”,只有这样你才需要路径“/”的路由处理程序,如下所示。
app.get("/", function(req, res) {
res.sendFile(path.join(__dirname, "dist/application/index.html"));
});
在 dist/application/index.html
中使用 "./"
引用的 JS 文件是相对于 dist 文件夹本身和 NOT dist/application
文件夹引用的。
您可以参考此 REPL 以获取更新的代码。 https://repl.it/repls/SoreFearlessNagware
试试下面的网址
/api/myarticles
- 由“/api”路由处理程序呈现
/api/myarticles.js
- 由静态资产中间件呈现,因为文件存在于 dist/api 文件夹中
/
- 使用“/”路由处理程序和 res.sendFile 呈现,因为 index.html 在 dist 文件夹中不存在。
/test.js
- 使用静态中间件呈现,因为文件存在于 dist 文件夹中
附加链接供参考。
1.Build 您的 angular 项目,使用 ng build
cmd 在服务器文件夹内部或外部。
2.To 在服务器中构建项目,更改 angular-cli
中的 dist
文件夹路径。
3.To 更改路径,使用 cli cmd 或编辑 angular-cli.json
文件的 "outDir": "./location/toYour/dist"
或者通过使用此 cli cmd ng build --output-path=dist/example/
4.Then 在您的服务器根文件中使用 express 包含静态 build/dist
文件夹。
5.Like这个app.use(express.static(path.join( 'your path to static folder')));
6.Now 重启你的服务器。