Ark*_*oss 3 http node.js cors axios
我正在使用Axios创建到其他域中的API服务器的HTTP请求。
http://localhost:3000。http://localhost:3000并从浏览器发出请求。到目前为止没有问题。跨域请求工作正常。但是,最近我想为这些API调用添加单元测试。这个测试环境是jsdom因为我正在使用Jest。当我从服务器端创建HTTP请求时,这引起了一个问题,原始请求设置为http://localhost,服务器不允许。
该请求是使用Axios发出的:
axios.post(`${API_DOMAIN}/member/account/login`, {
username,
password,
}, {
headers: {
Origin: 'http://localhost:3000'
}
})
Run Code Online (Sandbox Code Playgroud)
但是,回应仍显示
error: Cross origin http://localhost forbidden
如何将我在jsdom下使用Axios创建的HTTP请求的“来源”更改为other http://localhost?我需要它,http://localhost:3000以便API服务器允许我。
事实证明,这jsdom是发出源地址localhost并阻止跨源请求的人。从https://github.com/axios/axios/issues/1180,我能够解决我的问题。在测试套件中,将此代码放在axios的任何HTTP请求之前:
axios.defaults.adapter = require('axios/lib/adapters/http')
Run Code Online (Sandbox Code Playgroud)
这将使Axios使用NodeJS的HTTP适配器而不是JSDOM的XMLHttpRequests。这样就不会有跨域问题。
| 归档时间: |
|
| 查看次数: |
1797 次 |
| 最近记录: |