【发布时间】:2017-08-30 04:55:17
【问题描述】:
所以我正在尝试构建一个小型应用程序,该应用程序可以为网站提供服务,也可以为其提供 API。为此,我正在使用 Node、Express 和 Webpack。
目录看起来有点像这样:
>client
|>dist
|>src
>server
|>dist
|>src
>node_modules
package.json
webpack.config.js
Webpack 将每个 src 中的所有内容捆绑在一起,并将其输出到每个 dist 中,用于 client 和 server。
当我访问 / 时,我希望 Express 提供 client/dist 中的 index.html 文件。当我访问/api 时,我需要它来执行其他操作(这些操作正常)。
这就是我的server/src/app.js 文件的样子(谁处理路由):
const express = require('express');
const path = require('path');
const port = process.env.PORT || 5000;
const app = express();
app.get('/', function(req, res){
res.sendFile(path.resolve(__dirname, 'client', 'dist', 'index.html'));
console.log('got hit on / boy');
});
app.get('/api/', function(req, res) {
//Does the right thing
})
app.listen(port, function(){
console.log('listening on ' + port);
})
还有我的 Webpack 文件:
const path = require('path');
module.exports = [{
name: 'Client bundling',
entry: './client/src/app.js',
output: {
path: path.resolve(__dirname, 'client', 'dist', 'js'),
filename: 'bundle.js'
},
node: {
fs: 'empty',
net: 'empty'
}
},
{
name: 'Server bundling',
entry: './server/src/app.js',
output: {
path: path.resolve(__dirname, 'server', 'dist'),
filename: 'bundle.js'
},
node: {
fs: 'empty',
net: 'empty'
},
target: 'node'
}];
我的后续问题是如何从提供的视图访问 API 端点,因为它们都在同一个域中。
谢谢!
【问题讨论】:
-
可能最干净的方法是将 api 放在它自己的 Express 路由器中,然后使用
app.use('/api', apiRouter)路由到它。 -
从网页访问 API 很简单。只需使用 Ajax 调用
/api/xxx。 -
观察,__dirname 指向正在执行的模块的当前目录。在这种情况下,
server/src/这意味着 path.resolve(__dirname, 'client', 'dist', 'index.html') 将解析为不存在的server/src/client/dist/index.html。当您点击“/”时,您得到什么错误或响应? -
当我点击
/我得到Error: ENOENT: no such file or directory, stat 'C:\client\dist\index.html'@SelloMkantjwa -
@jfriend00 但即使使用单独的
apiRouter,我仍然需要访问index.html。我该怎么做?
标签: javascript node.js express routing