Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cross-Origin HTTP Request originating from server-side NodeJS/Axios/JSDOM

I am using Axios to create a HTTP request to a API server in different domain.

  • The API server allows Cross-Origin requests from http://localhost:3000.
  • I have no control over the API server.
  • My app usually runs in 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.

like image 416
Arkross Avatar asked Jun 27 '18 03:06

Arkross


1 Answers

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.

like image 111
Arkross Avatar answered Oct 20 '22 21:10

Arkross