koa项目发布到云服务器ESC的测试
空文件夹koa-server-test
npm init
安装koa模块
npm install koa
npm install koa-router //后面做路由用(也可以使用原生方法)
新建app.js入口文件
touch app.js
在编写代码之前,我们首先要明确,NodeJs目前只支持CommonJS规范,ES6的import…from在NodeJS是实验特性。
app.js:
const Koa = require('koa')
const Router = require('koa-router')
const app = new Koa() //app称作应用程序对象
const router = new Router({
prefix:"/api"
})
router.get('/', async ctx => {
let html = `
<ul>
<li><a href="/api/hello">helloworld</a></li>
<li><a href="/api/about">about</a></li>
</ul>
`
ctx.body = html
}).get('/hello', async (ctx) => {
ctx.body = 'helloworld'
}).get('/about', async (ctx) => {
ctx.body = 'about'
})
app.use(router.routes(), router.allowedMethods()) //注册路由
app.listen(3000)
利用FileZillar将koa-server-test文件夹上传到云服务器(略)
运行putty (putty安装略)
连接ESC服务器
//找到云服务器koa-server-test文件夹
npm install
node app.js //这里只做测试用,真正项目运行推荐使用pm2
显示报错,原因是3000端口被占用
- 查找系统正在使用的端口列表
netstat -lntp
- 查找监听端口号的进程PID
lsof -i :3000 //如果服务器command not found 可以yum install lsof来安装
- 杀死对应进程PID, 如13459
kill -9 13459
重新运行 app.js,阻塞状态运行成功,但是这时候我们是无法直接通过域名来访问到api接口的,需要对nginx进行配置
cd /etc/nginx
vim nginx.conf
我们首先要知道直接通过 www.xxx.com访问是默认带80端口,所有监听服务器的3000端口需要在nginx.conf下进行代理
server {
listen 80 default_server;
listen [::]:80 default_server;
server_name _;
root /usr/share/nginx/html;
# Load configuration files for the default server block.
include /etc/nginx/default.d/*.conf;
location / {
root /root/www/;
index index.html index.htm;
}
location /api/ {
proxy_pass http://127.0.0.1:3000; //表示监听
proxy_set_header Host $host;
}
error_page 404 /404.html;
location = /40x.html {
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
}
}
重新运行app.js,远程连接未断的时候可以通过 域名/api/test访问