axios / axios

Promise based HTTP client for the browser and node.js
https://axios-http.com
MIT License
105.43k stars 10.9k forks source link

Error: Cross origin http://localhost forbidden #1754

Closed serverlesspolska closed 4 years ago

serverlesspolska commented 6 years ago

Hi All,

I've got lambda function which I access via API Gateway. This function works ok when I test it via Postman or via this test which uses request library:

it('shoudl work via request', async () => {

        var options = { method: 'POST',
        url: 'https://-----------.execute-api.eu-central-1.amazonaws.com/dev/generate',
        headers: 
         { 
           'Cache-Control': 'no-cache',
           'Content-Type': 'application/json' },
        body: 
         { html: 'PGgxPkhlbGxvIHt7bmFtZX19PC9oMT48aDI+SGVsbG8gd29ybGQhISE8L2gyPg==',
           variables: 'eyJuYW1lIjoiV29ybGQiLCJwYXRoIjoiL2hvbWUvcGF3ZWwvLm52bS92ZXJzaW9ucy9ub2RlL3Y4LjExLjMvYmluOi91c3IvbG9jYWwvc2JpbjovdXNyL2xvY2FsL2JpbjovdXNyL3NiaW46L3Vzci9iaW46L3NiaW46L2JpbjovdXNyL2dhbWVzOi91c3IvbG9jYWwvZ2FtZXM6L3NuYXAvYmluOi91c3IvbGliL2p2bS9qYXZhLTgtb3JhY2xlL2JpbjovdXNyL2xpYi9qdm0vamF2YS04LW9yYWNsZS9kYi9iaW46L3Vzci9saWIvanZtL2phdmEtOC1vcmFjbGUvanJlL2JpbjovdmFyL3Rhc2sifQ==',
           css: 'aDEge2NvbG9yOiByZWR9' },
        json: true };

      request(options, function (error, response, body) {
        if (error) throw new Error(error);
        expect(body.generated).toBeTruthy()
        expect(body.pdf).toBeTruthy()
      });
    })

Problem

Unfortunately, when I'm using Axis I get following message Error: Cross origin http://localhost forbidden.

Could you please tell me what am I doing wrong?

My code looks like that:

   it('should work via axios', async () => {
        const event = {
            html: "PGgxPkhlbGxvIHt7bmFtZX19PC9oMT48aDI+SGVsbG8gd29ybGQhISE8L2gyPg==",
            variables: "eyJuYW1lIjoiV29ybGQiLCJwYXRoIjoiL2hvbWUvcGF3ZWwvLm52bS92ZXJzaW9ucy9ub2RlL3Y4LjExLjMvYmluOi91c3IvbG9jYWwvc2JpbjovdXNyL2xvY2FsL2JpbjovdXNyL3NiaW46L3Vzci9iaW46L3NiaW46L2JpbjovdXNyL2dhbWVzOi91c3IvbG9jYWwvZ2FtZXM6L3NuYXAvYmluOi91c3IvbGliL2p2bS9qYXZhLTgtb3JhY2xlL2JpbjovdXNyL2xpYi9qdm0vamF2YS04LW9yYWNsZS9kYi9iaW46L3Vzci9saWIvanZtL2phdmEtOC1vcmFjbGUvanJlL2JpbjovdmFyL3Rhc2sifQ==",
            css: "aDEge2NvbG9yOiByZWR9"
        }

        await axios.post(url, event, {
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json',
                },
                responseType: 'json',
                withCredentials: true,
            })
            .then(function (response) {
                console.log(response);
                // console.log('ok')
                expect(response.generated).toBeTruthy()
                expect(response.pdf).toBeTruthy()
            })
            .catch(function (error) {
                console.log(error);
            });
    })

Context

OpenGG commented 6 years ago

Possible duplicated: https://github.com/axios/axios/issues/1418

serverlesspolska commented 6 years ago

Thanks @OpenGG . adding const adapter = require('axios/lib/adapters/http') to the config solved the problem for me

morphatic commented 5 years ago

I also had this problem. This thread led me to this part of the Jest docs. I was able to fix the issue by pasting:

/**
 * @jest-environment node
 */

At the top of my test file. FWIW, adding:

{
  // ...
  "testEnvironment": "node"
  //...
}

to either jest.config.js or to my package.json file did not work for some reason. Not sure why...

wangdejun commented 5 years ago

I also had this problem. This thread led me to this part of the Jest docs. I was able to fix the issue by pasting:

/**
 * @jest-environment node
 */

At the top of my test file. FWIW, adding:

{
  // ...
  "testEnvironment": "node"
  //...
}

to either jest.config.js or to my package.json file did not work for some reason. Not sure why...

really thanks, this solves my problem

zlq4863947 commented 5 years ago

I solved this problem with the answer in the link below.

https://stackoverflow.com/questions/42677387/jest-returns-network-error-when-doing-an-authenticated-request-with-axios/43020260#43020260

dongyuanxin commented 5 years ago

I also had this problem. This thread led me to this part of the Jest docs. I was able to fix the issue by pasting:

/**
 * @jest-environment node
 */

At the top of my test file. FWIW, adding:

{
  // ...
  "testEnvironment": "node"
  //...
}

to either jest.config.js or to my package.json file did not work for some reason. Not sure why...

thanks very much! I use it in package.json:

{
  "scripts": {
    "test": "jest  --env=node"
  }
}

document: https://jestjs.io/docs/en/cli#env-environment

odusseys commented 4 years ago

I don't think the solution above is complete, often you will actually want to run your tests in the jsdom environment, if testing UI

chinesedfan commented 4 years ago

If using jest, users can set testURL to avoid CORS problem.

squalsoft commented 4 years ago

My jest.config.js resolves this issue (note testEnvironment without quotes): module.exports = { "transform": { "^.+\\.(ts|tsx)$": "ts-jest" }, testEnvironment: 'node' }

techieanant commented 4 years ago

Adding anything in my jest config was making other tests fail so adding the line below to my beforeAll function in my tests and it fixed the CORS error.

axios.defaults.adapter = require('axios/lib/adapters/http');

vidyamore commented 4 years ago

Added testEnvironment variable in the Jest.config file within module.exports module.exports = { rootDir: "../../", transform: {"^.+\.tsx?$": "ts-jest"}, setupFiles: ["./config/pact/pactSetup.ts"], moduleFileExtensions: ["ts", "js"], moduleNameMapper: { "^@src/(.)$": "/src/$1", "^@test/(.)$": "/test/$1" }, testRegex: "pact.ts$", testEnvironment:"node", setupFilesAfterEnv: ["./config/pact/pactTestWrapper.js"] };

It resolved the issue.