【问题标题】:Why Nuxtjs Axios Proxy is not working on server?为什么 Nuxtjs Axios 代理无法在服务器上运行?
【发布时间】:2021-10-18 00:45:24
【问题描述】:

几天来我一直在努力寻找解决方案。当我的网站投入生产时,似乎没有考虑我的 nuxt/axios 代理配置。本地一切正常,但是一旦站点在服务器上,我的 ajax 调用就会命中 mysite.com/api/ect... 而不是 mysite.com/api/v1/ect 的代理。我尝试使用 axios.baseURL 和各种配置,但似乎没有任何效果。

axios: {
    proxy: true,
    credentials: true,
},

proxy: {
    '/api/': { target: 'mysite.com/api/v1', pathRewrite: {'^/api/': ''} },
},

也许问题来自我的 Nginx 配置?我使用反向代理为 mysite.com 上的 nuxt 应用程序和 mysite.com/api 上的 laravel api 提供服务。会不会是这个问题?

# FORGE CONFIG (DO NOT REMOVE!)
include forge-conf/mysite.com/before/*;

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name mysite.com;
    server_tokens off;
    root /home/forge/api/public;

    # FORGE SSL (DO NOT REMOVE!)
    ssl_certificate /etc/nginx/ssl/....
    ssl_certificate_key /etc/nginx/ssl/....

    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers .....
    ssl_prefer_server_ciphers off;
    ssl_dhparam /etc/nginx/dhparams.pem;

    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-XSS-Protection "1; mode=block";
    add_header X-Content-Type-Options "nosniff";

    index index.html index.htm index.php;

    charset utf-8;

    # FORGE CONFIG (DO NOT REMOVE!)
    include forge-conf/mysite.com/server/*;

    location /api {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location = /favicon.ico { access_log off; log_not_found off; }
    location = /robots.txt  { access_log off; log_not_found off; }

    access_log off;
    error_log  /var/log/nginx/mysite.com-error.log error;

    error_page 404 /index.php;

    location ~ \.php$ {
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
        fastcgi_index index.php;
        include fastcgi_params;
    }
    
    location / {
        proxy_pass http://127.0.0.1:3000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }

    location ~ /\.(?!well-known).* {
        deny all;
    }
}

# FORGE CONFIG (DO NOT REMOVE!)
include forge-conf/mysite.com/after/*;

感谢您的帮助和推荐,

【问题讨论】:

  • axios 的 config.proxy 仅适用于 Node.js。在浏览器中是没有意义的。
  • 感谢您的回答,但我该如何继续?这是关于它的 NuxtJS 文档:axios.nuxtjs.org/options#proxy。正如在当地解释的那样,它工作得很好。只有当我将网站上线时,该 url 才不是由 axios 代理的
  • 你把env variables放到生产服务器了吗?
  • 是的。 API_URL 和 BASE_URL 已设置。但即使在代码中硬编码 url 也不起作用。

标签: laravel nginx proxy axios nuxt.js


【解决方案1】:
  1. 如果您使用代理模式,请不要使用 API_URL。使用prefix 代替。
  2. 打开调试以检查 proxyRequest:

nuxt.config.js 中的代理属性:

proxy: {
     
// target, others options

     logLevel: ‘debug’,

     onProxyReq(proxyReq, req, res) {

       // console.log here

     }
}

【讨论】:

    猜你喜欢
    • 2019-12-28
    • 1970-01-01
    • 2020-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-10
    • 2021-05-09
    • 1970-01-01
    相关资源
    最近更新 更多