M.H*_*Hol 2 node.js express angular
您好,我想express在节点服务器上运行我的应用程序。
我的 server.js :
var express = require('express');
var path = require('path');
var app = express();
app.get('/', (req, res) => {
res.sendFile(path.resolve('dist/my-app/index.html'))
});
app.listen(80, () => {
console.log('Server started!')
})
Run Code Online (Sandbox Code Playgroud)
但是当我尝试在localhost. 什么都没有出现。你能帮助我吗 ?
小智 9
Hope this would help you.
1) Run:
ng build --prod
Run Code Online (Sandbox Code Playgroud)
This will create a dist folder. Used for production.
2) Run:
npm install --save express
Run Code Online (Sandbox Code Playgroud)
To install express and save it as dependency in the project.
3) Create a file in root: ./server.js
4) Copy this code. Don't forget to modify with your name project
const express = require('express');
const http = require('http');
const path = require('path');
const app = express();
const port = process.env.PORT || 3001;
app.use(express.static(__dirname + '/dist/my-app-name'));
app.get('/*', (req, res) => res.sendFile(path.join(__dirname)));
const server = http.createServer(app);
server.listen(port, () => console.log(`App running on: http://localhost:${port}`));
Run Code Online (Sandbox Code Playgroud)
5) To run the server.js file
node server.js
Run Code Online (Sandbox Code Playgroud)
我找到了解决方案!
const express = require('express');
const app = express();
const path = require('path');
const fs = require('fs');
const port = process.env.NODE_PORT || 3000;
const root = path.join(__dirname, 'dist', 'my-app');
app.get('*' ,function(req, res) {
fs.stat(root + req.path, function(err){
if(err){
res.sendFile("index.html", { root });
}else{
res.sendFile(req.path, { root });
}
})
});
app.listen(port);
console.log('Listening on port '+ port);
Run Code Online (Sandbox Code Playgroud)
小智 1
示例 angularjs 应用程序目录位于此处:
AngularApp->myApp->
AngularApp->myApp->controllers
AngularApp->myApp->views
AngularApp->myApp->services
AngularApp->myApp->app.js
AngularApp->myApp->index.html
Run Code Online (Sandbox Code Playgroud)
创建一个 package.json 文件并在其中插入以下代码:
(位置:AngularApp->package.json)
{
"name": "myApp",
"version": "0.0.1",
"description": "My Project",
"dependencies": {
"express": "*"
},
"engine": "node >=0.6.x",
"scripts": {
"start": "node server.js"
},
"main": "server.js",
"repository": {
"type": "git",
"url": ""
},
"author": "myApp",
"license": "myApp",
"bugs": {
"url": ""
},
"homepage": "/"
}
Run Code Online (Sandbox Code Playgroud)
创建server.js:(位置:AngularApp->server.js)
var express = require('express');
var app = express();
app.use(express.static("myApp")); // myApp will be the same folder name.
app.get('/', function (req, res,next) {
res.redirect('/');
});
app.listen(8080, 'localhost');
console.log("MyProject Server is Listening on port 8080");
Run Code Online (Sandbox Code Playgroud)
导航到 package.json 文件后运行 commnad 'npm install'。
运行命令“npm start”。打开浏览器并点击 localhost:8080/
| 归档时间: |
|
| 查看次数: |
9761 次 |
| 最近记录: |