[英]How do you structure an Express application that serves API and views?
因此,我正在尝试构建一个小型应用程序,该应用程序可以为网站以及该网站的API提供服务。 我为此使用Node,Express和Webpack。
该目录看起来像这样:
>client
|>dist
|>src
>server
|>dist
|>src
>node_modules
package.json
webpack.config.js
Webpack捆绑了每个src
所有内容,并将其分发给client
和server
每个dist
。
当我访问/
我希望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'
}];
我的后续问题将是如何从服务的View访问API端点,因为它们都在同一个域中。
谢谢!
您指向的文件不存在。 改变这个
res.sendFile(path.resolve(__dirname, 'client', 'dist', 'index.html')
对此
res.sendFile(path.resolve("../..", 'client', 'dist', 'index.html')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.