# 问题概述
刚刚在 NodeJS
环境下对服务端接口进行 Jest
单元测试时发现 axios
报错, 说是出现了跨域请求.
Error: Cross origin http://localhost forbidden
at dispatchError (\node_modules\jsdom\lib\jsdom\living\xhr\xhr-utils.js:62:19)
at Object.validCORSHeaders (\node_modules\jsdom\lib\jsdom\living\xhr\xhr-utils.js:74:5)
at receiveResponse (\node_modules\jsdom\lib\jsdom\living\xhr\XMLHttpRequest-impl.js:797:19)
at Request.<anonymous> (\node_modules\jsdom\lib\jsdom\living\xhr\XMLHttpRequest-impl.js:658:36)
at Request.emit (events.js:315:20)
at Request.onRequestResponse (\node_modules\request\request.js:1059:10)
at ClientRequest.emit (events.js:315:20)
at HTTPParser.parserOnIncomingClient [as onIncoming] (_http_client.js:641:27)
at HTTPParser.parserOnHeadersComplete (_http_common.js:126:17)
at Socket.socketOnData (_http_client.js:509:22) undefined
确认服务端没有对 localhost
进行跨域限制, 并且请求也不是从浏览器环境发起的后, 推断是 axios
或者测试环境 Jest
出现了问题.
# 解决方案
向 package.json
文件的 jest
块中加入 testEnvironment
配置项, 并将其指定为 node
即可.
package.json:
{
// ...
"jest":{
"testEnvironment": "node"
}
}
# 参考
- Jest 配置项: testEnvironment (opens new window):
testEnvironment Default: "jsdom" The test environment that will be used for testing. The default environment in Jest is a browser-like environment through jsdom. If you are building a node service, you can use the node option to use a node-like environment instead.
- Error: Cross origin http://localhost forbidden (opens new window)
# 推广
欢迎大家点击下方的图片领取限量 阿里云优惠券 (opens new window), 新购续费更优惠: (opens new window)