gpt4 book ai didi

node.js - 如何使用 Node 运行后端服务器?

转载 作者:搜寻专家 更新时间:2023-11-01 00:16:19 28 4
gpt4 key购买 nike

我正在学习 Vue.js 并从基本模板 vue init webpack my-project 开始,我想运行一个后端。

前端是使用 webpack 启动的,但是我的 server.js 文件必须使用 node server.js 单独启动。我怎样才能一起启动它们?

我搜索了一些基本示例,但很难找到。

目前我的 package.json 中有这个:

{
"scripts": {
"client": "webpack-dev-server --inline --progress --config build/webpack.dev.conf.js",

"server": "nodemon src/server/server.js --exec babel-node"
},
// ...
}

这很好,但是客户端和服务器在不同的端口上运行。在生产应用程序中,我只需要使用一个端口。

这怎么可能?

最佳答案

在生产环境中

这是我通常的部署策略

I use Nginx as a static web server and HTTP proxy

I use pm2 to mange node API

PM2 是一款出色的流程管理器工具,具有多项功能

So what you need to is build (probably npm run build) your vue js app then you will get your static assets a dist/build folder containing just static content with index.html as an entry point

像下面这样用 pm2 启动你的 Node 服务器

pm2 start server.js --name='api'

这是一个示例 Nginx 配置代理 Node API 并提供它在 /etc/nginx/sites-available/default 中找到的静态内容

server {
listen *:80;

server_name localhost; ## could be www.yourdomain.com

location / {
root /home/me/myapp/dist; # your app build path
try_files $uri index.html;
}
location /api {
proxy_pass http://localhost:5678/api;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
proxy_connect_timeout 600000;
proxy_send_timeout 600000;
proxy_read_timeout 600000;
send_timeout 600000;

gzip on;
gzip_proxied any;
gzip_types
application/json;

}

So what you basically get is your Vue app at port 80 the default so you don't have to specify the port and your API will be at /api so your vue app will be at youdomain.com and the API at youdomain.com/api

在开发环境中

我通常不介意使用两个命令启动我的 API 和前端。我因此在单独的终端中启动它们以分别调试和开发。

if you really care about starting them in the single command

你可以做的是在你的 package.json 中创建一个新命令

"start":"npm run server && npm run client"

关于node.js - 如何使用 Node 运行后端服务器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50349411/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com