在我看来,你有两种方法可以解决这个问题:
首先,有一个名为devServer 的字段,您可以通过它调整运行npm run serve 时启动的开发服务器的配置。具体来说,您要注意proxy 字段,您可以使用该字段要求开发服务器将某些请求路由到您的节点后端。
其次,根据您的设置,您可以完全使用不同的host 来处理后端调用。例如,正如您提到的,开发服务器默认运行在8080 上。您可以将节点后端设置为在 8081 上运行,并且您在 VueJS 应用程序中发出的所有后端请求都将明确使用 <host>:8081 的主机。当您决定将代码投入生产并获得 SSL 证书时,您可以使用 Nginx 之类的反向代理服务器将所有请求从 api.example.com 重定向到端口 8081。
关于与 MongoDB、IMO 的连接,您应该问自己一个问题:
为客户提供对数据库的直接访问是否安全?
如果答案是肯定的,那么请务必确保 mongoDB 服务器在启用其 HTTP 接口的情况下启动,设置一些访问限制,更新proxy 和/或nginx,一切顺利。
如果答案是否定的,那么您将不得不在您的 NodeJS 应用程序中编写轻量级 API 端点。例如,不是允许用户直接与数据库对话以获取他们的权限列表,而是通过GET /api/privileges 向您的 NodeJS 应用程序发出请求,您的 NodeJS 应用程序将依次与您的数据库通信以获取此数据并将其返回给客户。
让后端与您的数据库而不是客户端对话的另一个好处是,您的数据库实例的详细信息永远不会暴露给恶意客户端。
这是我在我的一个网站上的vue.config.js 设置示例:
const proxyPath = 'https://api.example.com'
module.exports = {
devServer: {
port: 8115, // Change the port from 8080
public: 'dev.example.com',
proxy: {
'/api/': {
target: proxyPath
},
'/auth/': {
target: proxyPath
},
'/socket.io': {
target: proxyPath,
ws: true
},
'^/websocket': {
target: proxyPath,
ws: true
}
}
}
}
这是同一开发服务器的 nginx 配置。为了安全起见,我迅速从我们的生产配置中提取了我所能做的,并隐藏了某些字段。将此视为伪代码(伪配置?)。
server {
listen 443 ssl;
server_name dev.example.com;
root "/home/www/workspace/app-dev";
set $APP_PORT "8115";
location / {
# Don't allow robots to access the dev server
if ($http_user_agent ~* "baiduspider|twitterbot|facebookexternalhit|rogerbot|linkedinbot|embedly|quora link preview|showyoubot|outbrain|pinterest|slackbot|vkShare|W3C_Validator|Googlebot") {
return 404;
}
# Redirect all requests to the vue dev server @localhost:$APP_PORT
proxy_pass $scheme://127.0.0.1:$APP_PORT$request_uri;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $http_connection;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
server {
listen 443 ssl;
server_name api.example.com;
set $APP_PORT "8240";
location / {
# Don't allow robots to access the dev server
if ($http_user_agent ~* "baiduspider|twitterbot|facebookexternalhit|rogerbot|linkedinbot|embedly|quora link preview|showyoubot|outbrain|pinterest|slackbot|vkShare|W3C_Validator|Googlebot") {
return 404;
}
# Redirect all requests to NodeJS backend @localhost:$APP_PORT
proxy_pass $scheme://127.0.0.1:$APP_PORT$request_uri;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $http_connection;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}