【问题标题】:Vue will not communicate with Express through NGINXVue 不会通过 NGINX 与 Express 通信
【发布时间】:2020-08-01 23:40:37
【问题描述】:

我在 DigitalOcean 液滴上设置了 Vue 前端和 Express 后端,我正在使用 NGINX 让它们通过 API 进行对话。前端工作正常,但是当我尝试访问 API 路由时,我在控制台中收到“CONNECTION_REFUSED”错误。错误指向 webpack 中的 axios。我认为我已经正确配置了 NGINX(请参见下面的代码),并且当我使用 curl 访问 API 路由时它可以工作。

在前端,我让 axios 向后端发送请求,然后后端返回 json 数据。

问题 1: 如果 NGINX 现在正在处理 Vue 和 Express 之间的通信,我认为我可以摆脱 axios 是否正确,因为当发出 API 请求时 NGINX 决定如何处理它(将其发送到后端,然后发送响应到客户端),它有效地绕过了 axios 与 Express 的通信?这是 axios 代码(api.js 只是导入 axios 并设置基本 url):

import api from '@/services/api'

export default {
  fetchProjects () {
    return api().get('projects')
  },
  fetchProjectById (id) {
    return api().get(`projects/${id}`)
  }

问题 2: 我在前端使用 https,但通过 http 与后端通信。在 Firefox 上,我收到“CORS 请求未成功” - 我隐约记得在某处读到 https 到 http 可能会导致 CORS 出现问题。这可能是问题吗?如果是这样,我可以为后端和前端使用相同的 SSL 证书吗?我需要更改 NGINX 配置中的任何内容吗?

我已经为此工作了好几天,但我这辈子都想不通。任何帮助将不胜感激。

upstream backend {
server 127.0.0.1:3000;
keepalive 8;
}

server {
    listen 443 ssl default_server;
    listen [::]:443 ssl default_server;

    root /var/www/html/PersonalWebsite/frontend/dist;

    index index.html index.htm index.nginx-debian.html;

    server_name website.com www.website.com;
    ssl_certificate <link-to-cert>;
    ssl_certificate_key <link-to-key>;
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

    # Redirect to https
    if ($scheme != "https") {
            return 301 https://$host$request_uri;
    } # managed by Certbot

    location / {

            add_header 'Access-Control-Allow-Origin' 'http://localhost:8080' always;
            add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE' always;
            add_header 'Access-Control-Allow-Headers' 'X-Requested-With,Accept,Content-Type, Origin' 
            always;
            try_files $uri $uri/ =404;


    }

    location /api/ {
            add_header 'Access-Control-Allow-Origin' 'http://localhost:3000' always;
            add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE' always;
            add_header 'Access-Control-Allow-Headers' 'X-Requested-With,Accept,Content-Type, Origin' 
            always;

            proxy_set_header X-Forwarded-Proto $scheme;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

            proxy_pass http://backend;

    }

}

【问题讨论】:

    标签: node.js api vue.js nginx axios


    【解决方案1】:

    错误可能是因为“cors”,但您是否尝试过使用“postman”?这个链接可以帮助你https://www.npmjs.com/package/cors#usage
    https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

    【讨论】:

    • 是的,最终是 CORS。它具有来自开发环境的旧 IP。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-29
    • 2012-07-11
    • 1970-01-01
    • 1970-01-01
    • 2019-12-23
    • 1970-01-01
    相关资源
    最近更新 更多