Tag Archives: Java stepping pit series

How to Solve Swagger error: typeerror: failed to fetch

Scene description

A project was recently deployed. Because it is compatible with IE8, the front and back ends need to be deployed to a site. The nginx configuration is as follows:

server {
    listen       80;
    server_name www.aaa.ink;
	client_max_body_size  1000M;
	client_body_timeout 20s;
	client_header_timeout 10s;
	send_timeout 30s;
	ssl_protocols TLSv1.2;
    charset utf-8;
	location ^~ /api/ {
		proxy_pass http://127.0.0.1:8080/api/;
	}
    
    location ~/(.*)$ {
        root   /usr/local/nginx/ttm;
        index  index.html index.htm;
    }
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   html;
    }
}

Swagger is used as the interface document in the background. After the project is started, the site can be accessed normally, but an error will be reported when testing the interface in swagger. The error prompt is typeerror: failed to fetch

Problem analysis

Analysis shows that swagger’s actual request address becomes http://127.0.0.1:8080/api/ , it’s not what we actually do http://www.aaa.ink/api/ Interface address. It is found that swagger will obtain a server address according to the user’s request. Due to the use of nginx reverse proxy, swagger obtained the intranet address we configured, resulting in the request unable to respond normally.

Problem solving

location ^~ /api/ {
	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;
	proxy_set_header X-Forwarded-Host $server_name;
	proxy_pass http://127.0.0.1:8080/api/;
}

Set the forwarding of background items to the request header so that swagger can get the real address. The problem can be solved.