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

时间:2018-04-22 07:07:21

标签: javascript node.js api

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

当我想使用Jest + supertest为我的api编写测试时,当我测试访问远程LOL api的路由时,总是会出现此错误

Response for preflight has invalid HTTP status code 401

当然,当我使用http客户端或webbrowser

时,我从未收到此错误

测试方法

 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 }

1 个答案:

答案 0 :(得分:3)

已解决 -

默认情况下,jest是jsdom模式下的跑步者,这意味着jest在浏览器中是跑步者,默认情况下是envirement,

需要做的是将其配置为在服务器中运行,如envirement 你需要把它放在你的jest.config文件中

value