为什么 Swagger UI 中会出现“服务器无响应”的情况?
我的 API 调用在 Postman 中正常工作。但是当我从 Swagger UI 发送请求时,所有请求都显示“服务器无响应”:
Response Body
no contentResponse Code
0Response Headers
{ "error": "no response from server" }
问题可能是什么以及如何解决?
浏览器控制台显示以下错误:
Failed to load resource: net::ERR_CONNECTION_REFUSED
Uncaught TypeError: Cannot read property 'length' of undefined
at showStatus (index.js:24)
at showErrorStatus (index.js:24)
at error (index.js:607) at spec-converter.js:533
at Request.callback (index.js:24)
at Request.crossDomainError (index.js:24)
at XMLHttpRequest.xhr.onreadystatechange (index.js:24)
net::ERR_CONNECTION_REFUSED
听起来您需要在本地主机上启用 CORS,以便它在响应中发送
Access-Control-Allow-Origin: *
标头。如何执行此操作取决于您使用的服务器。更多信息请点击这里:
https://enable-cors.org/server.html
https://github.com/swagger-api/swagger-ui/#cors-support
您可能还需要允许 OPTIONS 预检请求 。
由于序列化器响应中的引用循环,Swagger 返回 0 响应代码。
在获取序列化器响应时忽略引用循环。
如果您使用的是 Web API,请使用以下代码
services.AddMvc()
.AddJsonOptions(opt =>
{
opt.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
});
从 swagger 配置 json 文件(在我的情况下是 tsoa.json)中删除方案并重新启动服务器。它对我有用。
{
"readme": "https://github.com/lukeautry/tsoa/blob/HEAD/tsoa.json",
"swagger": {
"outputDirectory": "./dist/src",
"entryFile": "./src/server.ts",
"basePath": "/",
"schemes": [
"http",
"https"
],
"securityDefinitions": {
"basic": {
"type": "basic"
}
}
},
"routes": {
"basePath": "/",
"entryFile": "./src/server.ts",
"routesDir": "./src",
"authenticationModule": "./src/security/Authentication"
}
}