I am using Axios to create a HTTP request to a API server in different domain.
http://localhost:3000
.http://localhost:3000
and makes requests from browser.There's no problem up to this point. Cross-Origin requests are working fine. However, recently I want to add a unit test for those API calls. This test environment is jsdom
since I'm using Jest
. This raises a problem when I create HTTP request from server-side, the origin is set to http://localhost
, which the server does not allow.
The request is made using Axios:
axios.post(`${API_DOMAIN}/member/account/login`, {
username,
password,
}, {
headers: {
Origin: 'http://localhost:3000'
}
})
However, the response still says that
error: Cross origin http://localhost forbidden
How to change the "Origin" of the HTTP request I create with Axios under jsdom to other than http://localhost
? I need it to be http://localhost:3000
so that the API server allows me.
It turns out jsdom
is the one who makes the origin localhost
, and prevented cross-origin requests. From https://github.com/axios/axios/issues/1180 I was able to solve my problem. In the test suite, place this code before any HTTP requests by axios:
axios.defaults.adapter = require('axios/lib/adapters/http')
This will make Axios use NodeJS's HTTP adapter instead of JSDOM's XMLHttpRequests. This way there will be no Cross-origin problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With