koa项目部署到云服务器上并可通过域名访问接口

koa项目发布到云服务器ESC的测试

空文件夹koa-server-test

npm init

npm初始化环境
安装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访问
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值