Swagger UI - “ TypeError: Failed to fetch” on vali

2020-02-08 16:11发布

问题:

I've just pulled down the latest Swagger from the Git repo (3.0.19) using: https://github.com/swagger-api/swagger-ui.git and updated my API to use the new version.

Ran git describe --tags to confirm and my version is currently: v3.0.19-6-gaab1403

The problem I'm having is one described here, whereby my response is a 403 (I can see this in the inspector on the browser) and although I have a reponse for error 403, I still get the TypeError: Failed to fetch message.

Here's a snippet from my definition regarding the 403 response:

                    "403": {
                    "description": "Forbidden",
                    "headers": {
                        "Access-Control-Allow-Origin": {
                            "type": "string"
                        }
                    }
                },

I've also noticed it reported here however, I know it's not a CORS issue as I have tested the endpoints and the OPTIONS are returning correct, as are the endpoints if called with valid information (I force this 403).

Could anyone point me in the right direction please?

Update: I have since tested on a 401 response, with the same response.

And that a 400 is working as expected:

回答1:

For anyone that runs into this problem;

After a day of troubleshooting and the Swagger support guys pointing me in the right direction, it turns out that this is currently caused by a bug within the AWS API Gateway custom authorizers.

We are currently using AWS API Gateway for managing our APIs, this includes managing all our authorization via a custom authorizer. The issue is that custom authorizers do not currently support passing through headers within the response and Swagger UI needs the Access-Control-Allow-Origin:* within the response header(s) to display the correct HTTP status code.

See this AWS thread regarding the issue (which is older than a year already):

https://forums.aws.amazon.com/thread.jspa?messageID=728839

Swagger UI discussion on same: https://github.com/swagger-api/swagger-ui/issues/3403

EDIT / UPDATE

This has since been resolved with the use of Gateway Responses. See this same forum (page 2):

https://forums.aws.amazon.com/thread.jspa?messageID=728839



回答2:

I hit this error during local development (i.e., had nothing to do with AWS). The underlying cause (CORS violation) is identical. The following might help others who encounter this problem.

I setup connexion with an openapi spec that referred to http://localhost:9090/. When the development server starts, it says "Running on http://0.0.0.0:9090/". That page appears to work, but the swagger ui uses http://localhost:9090/ from the openapi spec for subsequent requests and shows TypeError: Failed to fetch in results. The browser console shows Access to fetch at 'http://localhost:9090/vr/variation' from origin 'http://0.0.0.0:9090'. The provided curl command worked fine; although initially confusing, the curl success is a clue that the problem is due to browser blocking rather than server-side failure.

(Connexion is based on Python flask and provides extended support for openapi integration.)



回答3:

Because the problem of cross-origin means your website is hosted on either locally or with port 8000 or different port, and your swagger's port number is different, so this problem is genuine. We can fix it by giving permission.

Here is the node code:

app.use( (request, response, next) => {
    response.header("Access-Control-Allow-Origin", "*");
    response.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
});

We can solve by using CORS npm as well. https://www.npmjs.com/package/cors



回答4:

Disclaimer:- This answer is for APIs developed using Asp.net Core

I have faced similar issue when trying to access the APIs from the Swagger UI Editor. I was trying to access some APIs developed using Asp.net Core where as the Swagger UI Editor was hosted on Apache. I was facing CORS (Cross Orgin Request).

I have to modify my APIs code to allow CORS request using following code:- Declare within Startup.cs File having class "StartupShutdownHandler"

private readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";

Added a section of code within ConfigureServices Method.

var str = ConfigurationHandler.GetSection<string>(StringConstants.AppSettingsKeys.CORSWhitelistedURL);
        if (!string.IsNullOrEmpty(str))
        {
            services.AddCors(options =>
            {
                options.AddPolicy(MyAllowSpecificOrigins,
                builder =>
                {
                    builder.WithOrigins(str);
            });
            });
        }

Added a line of code within Configure Method.

 app.UseCors(MyAllowSpecificOrigins);

Reference Enable Cross-Origin Requests (CORS) in ASP.NET Core



回答5:

Please check the swaggerOptions provided to swagger jsdoc and check whether host and base name is correct. I have encountered the same issue before and got fixed the issue by correcting this. Hope this will also solve the problem.

Eg:

const options = {
  swagger: "2.0",
  swaggerDefinition: {
    // options.swaggerDefinition could be also options.definition
    info: {
      title: "Customer API", // Title (required)
      description: "Dummy Customer API for implementing swagger",
      contact: {
        name: "Stack Overflow"
      },
      version: "1.0.0" // Version (required)
    },
    host: "localhost:5000",
    basePath: "/"
  },
  // Path to the API docs
  apis: ["SwaggerImplementation/index.js"] // For complex api's pass something like apis: ["./routes/*.js"]
};