gpt4 book ai didi

javascript - 预检响应具有无效的 HTTP 状态代码 401 - 测试

转载 作者:行者123 更新时间:2023-11-30 09:23:56 36 4
gpt4 key购买 nike

所以我使用 nodejs 从我的服务器访问 API(英雄联盟 api),我测试了使用 httpie(一个简单的 http 客户端)访问 api 的路由,一切正常没有任何问题。

当我想使用 Jest + supertest 为我的 api 编写测试时,以及当我测试访问远程 LOL api 的路由时, 总是得到这个错误

预检响应具有无效的 HTTP 状态代码 401

当然,当我使用 http 客户端或网络浏览器时,我永远不会收到此错误

测试方法

 test('exist route should return 200 if summoner exist', done => {
request(app)
.get('/summoners/exist/yaskillin')
.expect('Content-Type', /json/)
.expect(200)
.then(res => {
expect(res.body.exist).toBeTruthy()
done()
})
})

路由方法

private exist(req: Request, res: Response, next: NextFunction) {
let name: string = req.params["name"];


return this.riotService
.getSummonerByName(name)
.then(result => {
console.log(result)
res.json({ exist: true });
})
.catch(err => {
console.log(err.config)
res.json({ exist: false });
});
}

错误

console.error node_modules/jsdom/lib/jsdom/virtual-console.js:29
Error: Error: Response for preflight has invalid HTTP status code 401
at Object.dispatchError (/home/ssd/Dev/Project/lolnafrica/backend/node_modules/jsdom/lib/jsdom/living/xhr-utils.js:65:19)
at EventEmitter.client.on.err (/home/ssd/Dev/Project/lolnafrica/backend/node_modules/jsdom/lib/jsdom/living/xmlhttprequest.js:664:20)
at EventEmitter.emit (events.js:185:15)
at Request.preflightClient.on.resp (/home/ssd/Dev/Project/lolnafrica/backend/node_modules/jsdom/lib/jsdom/living/xhr-utils.js:373:16)
at Request.emit (events.js:180:13)
at Request.onRequestResponse (/home/ssd/Dev/Project/lolnafrica/backend/node_modules/request/request.js:1068:10)
at ClientRequest.emit (events.js:180:13)
at HTTPParser.parserOnIncomingClient [as onIncoming] (_http_client.js:539:21)
at HTTPParser.parserOnHeadersComplete (_http_common.js:117:17)
at TLSSocket.socketOnData (_http_client.js:444:20) undefined

错误对象

{ Error: Network Error
at createError (/home/ssd/Dev/Project/lolnafrica/backend/node_modules/axios/lib/core/createError.js:16:15)
at XMLHttpRequest.handleError (/home/ssd/Dev/Project/lolnafrica/backend/node_modules/axios/lib/adapters/xhr.js:87:14)
at XMLHttpRequest.el.addEventListener.event (/home/ssd/Dev/Project/lolnafrica/backend/node_modules/jsdom/lib/jsdom/living/helpers/create-event-accessor.js:33:32)
at invokeEventListeners (/home/ssd/Dev/Project/lolnafrica/backend/node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:193:27)
at XMLHttpRequestEventTargetImpl._dispatch (/home/ssd/Dev/Project/lolnafrica/backend/node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:119:9)
at XMLHttpRequestEventTargetImpl.dispatchEvent (/home/ssd/Dev/Project/lolnafrica/backend/node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:82:17)
at XMLHttpRequest.dispatchEvent (/home/ssd/Dev/Project/lolnafrica/backend/node_modules/jsdom/lib/jsdom/living/generated/EventTarget.js:157:21)
at requestErrorSteps (/home/ssd/Dev/Project/lolnafrica/backend/node_modules/jsdom/lib/jsdom/living/xhr-utils.js:132:7)
at Object.dispatchError (/home/ssd/Dev/Project/lolnafrica/backend/node_modules/jsdom/lib/jsdom/living/xhr-utils.js:62:3)
at EventEmitter.client.on.err (/home/ssd/Dev/Project/lolnafrica/backend/node_modules/jsdom/lib/jsdom/living/xmlhttprequest.js:664:20)
at EventEmitter.emit (events.js:185:15)
at Request.preflightClient.on.resp (/home/ssd/Dev/Project/lolnafrica/backend/node_modules/jsdom/lib/jsdom/living/xhr-utils.js:373:16)
at Request.emit (events.js:180:13)
at Request.onRequestResponse (/home/ssd/Dev/Project/lolnafrica/backend/node_modules/request/request.js:1068:10)
at ClientRequest.emit (events.js:180:13)
at HTTPParser.parserOnIncomingClient (_http_client.js:539:21)
at HTTPParser.parserOnHeadersComplete (_http_common.js:117:17)
at TLSSocket.socketOnData (_http_client.js:444:20)
at TLSSocket.emit (events.js:180:13)
at addChunk (_stream_readable.js:269:12)
at readableAddChunk (_stream_readable.js:256:11)
at TLSSocket.Readable.push (_stream_readable.js:213:10)
at TLSWrap.onread (net.js:581:20)
config:
{ adapter: [Function: xhrAdapter],
transformRequest: { '0': [Function: transformRequest] },
transformResponse: { '0': [Function: transformResponse] },
timeout: 0,
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
validateStatus: [Function: validateStatus],
headers:
{ Accept: 'application/json, text/plain, */*',
'Accept-Charset': 'application/x-www-form-urlencoded; charset=UTF-8',
'X-Riot-Token': 'RGAPI-3467f48f-6e15-4bb2-8ebf-8d2acecac233',
'Accept-Language': 'en-US,en;q=0.9,fr;q=0.8' },
method: 'get',
baseURL: 'https://euw1.api.riotgames.com/lol/',
url: 'https://euw1.api.riotgames.com/lol/summoner/v3/summoners/by-name/yaskillin',
data: undefined },
request:
XMLHttpRequest {
upload: XMLHttpRequestUpload { _ownerDocument: [Document] },
_registeredHandlers: Set { 'readystatechange' },
_eventHandlers: { readystatechange: [Function: handleLoad] },
[Symbol(flag)]:
{ synchronous: false,
withCredentials: false,
mimeType: null,
auth: null,
method: 'GET',
responseType: '',
requestHeaders: [Object],
referrer: 'about:blank',
uri: 'https://euw1.api.riotgames.com/lol/summoner/v3/summoners/by-name/yaskillin',
timeout: 0,
body: undefined,
formData: false,
preflight: true,
requestManager: [RequestManager],
pool: undefined,
agentOptions: undefined,
strictSSL: undefined,
proxy: undefined,
cookieJar: [CookieJar],
encoding: 'UTF-8',
origin: 'null',
userAgent: 'Mozilla/5.0 (linux) AppleWebKit/537.36 (KHTML, like Gecko) jsdom/11.6.2' },
[Symbol(properties)]:
{ beforeSend: false,
send: false,
timeoutStart: 0,
timeoutId: 0,
timeoutFn: null,
client: [EventEmitter],
responseHeaders: {},
filteredResponseHeaders: [],
responseBuffer: null,
responseCache: null,
responseTextCache: null,
responseXMLCache: null,
responseURL: '',
readyState: 4,
status: 0,
statusText: '',
error: Error: Response for preflight has invalid HTTP status code 401
at Request.preflightClient.on.resp (/home/ssd/Dev/Project/lolnafrica/backend/node_modules/jsdom/lib/jsdom/living/xhr-utils.js:373:30)
at Request.emit (events.js:180:13)
at Request.onRequestResponse (/home/ssd/Dev/Project/lolnafrica/backend/node_modules/request/request.js:1068:10)
at ClientRequest.emit (events.js:180:13)
at HTTPParser.parserOnIncomingClient (_http_client.js:539:21)
at HTTPParser.parserOnHeadersComplete (_http_common.js:117:17)
at TLSSocket.socketOnData (_http_client.js:444:20)
at TLSSocket.emit (events.js:180:13)
at addChunk (_stream_readable.js:269:12)
at readableAddChunk (_stream_readable.js:256:11),
uploadComplete: true,
uploadListener: false,
abortError: false,
cookieJar: [CookieJar],
bufferStepSize: 1048576,
totalReceivedChunkSize: 0,
requestBuffer: null,
requestCache: null,
origin: 'null' } },
response: undefined }

最佳答案

已解决——

默认情况下,jest在jsdom模式下运行,也就是说jest在浏览器环境下默认运行,

需要做的是将其配置为在类似环境的服务器中运行你需要把它放在你的 jest.config 文件中

"testEnvironment": "node",

关于javascript - 预检响应具有无效的 HTTP 状态代码 401 - 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49963437/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com