Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

responseType=text but json is parsed #2791

Closed
neg3ntropy opened this issue Mar 2, 2020 · 11 comments
Closed

responseType=text but json is parsed #2791

neg3ntropy opened this issue Mar 2, 2020 · 11 comments

Comments

@neg3ntropy
Copy link

neg3ntropy commented Mar 2, 2020

Describe the bug

I want to get a response as string even if that comes as application/json. Parsing the response to an object is not required and not desired as the only thing I have to do with it is rewrite some urls and I am not sure of the content type the server will use.

To Reproduce

Server:

const http = require("http");
const server = http.createServer((req, res) => {
    res.writeHead(200, {"Content-Type": "application/json"});
    res.end("{\"doNotParse\": 1}");
});
server.listen(1234);

Client:

const axios = require("axios");   
axios.request({url: "http://localhost:1234/", responseType: "text"})
     .then(res => console.log("Type of data is %s", typeof res.data));

Outcome:

Type of data is object

Expected behavior
response data should be the string "{\"doNotParse\": 1}", the program would print:

Type of data is string

Environment:

  • Axios 0.19.2
  • Fedora 31
  • Node 12

Additional context/Screenshots
Setting transformResponse: (data) => data appears to do the trick, regardless of responseType.

@determin1st
Copy link

determin1st commented Mar 2, 2020

What you think should be the default content type returned in the case of this option enabled:

  • ArrayBuffer
  • String

I'm asking, because in browser, for example, may be Response object which is the "raw" response, or any of these

@neg3ntropy
Copy link
Author

I am not familiar with browsers, but it looks like responseType=text should result in strings. For ArrayBuffer there's responseType=arraybuffer.

@determin1st
Copy link

determin1st commented Mar 3, 2020

did you try using axios config with responseType option? (pre-created instance)

@neg3ntropy
Copy link
Author

you can see that from the code posted "to reproduce".

@determin1st
Copy link

determin1st commented Mar 5, 2020

oke, tested..

    axios({
      url: "http://localhost:1234/",
      //responseType: "text",
      transformResponse: []
    }).then(function(res) {
      console.log("Type of data is %s", typeof res.data);
    });

that happens because of transformResponse has one function which transforms from JSON, so you may make it empty to opt-out of this behaviour. maybe it should clean-up the default JSON thing, im not sure how responseType option should operate...

@sagar-gavhane
Copy link

What do you think about this?

const instance = axios.create({
  baseURL: 'https://jsonplaceholder.typicode.com/',
  transformResponse: (data) => JSON.stringify(data)
});

const fetchUserInStringType = async () => {
  const response = await instance.get('/users/1')  
  console.log(response.data)
}

fetchUserInStringType()

@determin1st
Copy link

the main thought here, is why one option is choosen against another. should they depend on each other and stuff..

@liesauer
Copy link

+1

const response = await axios.get(url, {
    responseType: 'text',
    transformResponse: [data => data],
});
// get html string or others string
console.log(response.data);

works for me, but honestly, this is really bad...setting responseType to text suppose to return string but do nothing actually and keep trying to parse as json with no reason...

andrewkroh added a commit to andrewkroh/beats-playground that referenced this issue Feb 25, 2021
When JSON logs are returned this avoid decoding them.

It's using a workaround from axios/axios#2791 (comment).
DigitalBrainJS added a commit to DigitalBrainJS/axios that referenced this issue Mar 19, 2021
jasonsaayman pushed a commit that referenced this issue Apr 19, 2021
…be passed directly as payload for encoding to JSON #2613, #61, #907 (#3688)

* Draft

* Added support for primitive types to be converted to JSON if the request Content-Type is 'application/json';
Added throwing SyntaxError if JSON parsing failed and responseType is json;
Added transitional option object;
Added options validator to assert transitional options;
Added transitional option `silentJSONParsing= true` for backward compatibility;
Updated README.md;
Updated typings;

* Fixed isOlderVersion helper;
Fixed typo;
Added validator.spec.js;

* Added forcedJSONParsing transitional option #2791

* `transformData` is now called in the default configuration context if the function context is not specified (for tests compatibility);

* Added `transitional.clarifyTimeoutError` to throw ETIMEDOUT error instead of generic ECONNABORTED on request timeouts;
Added support of onloadend handler if available instead of onreadystatechange;
Added xhr timeout test;
Fixed potential bug of xhr adapter with proper handling timeouts&errors (FakeXMLHTTPRequest failed to handle timeouts);
jasonsaayman pushed a commit that referenced this issue Apr 19, 2021
* Draft

* Added support for primitive types to be converted to JSON if the request Content-Type is 'application/json';
Added throwing SyntaxError if JSON parsing failed and responseType is json;
Added transitional option object;
Added options validator to assert transitional options;
Added transitional option `silentJSONParsing= true` for backward compatibility;
Updated README.md;
Updated typings;

* Fixed isOlderVersion helper;
Fixed typo;
Added validator.spec.js;

* Added forcedJSONParsing transitional option #2791

* `transformData` is now called in the default configuration context if the function context is not specified (for tests compatibility);

* Added `transitional.clarifyTimeoutError` to throw ETIMEDOUT error instead of generic ECONNABORTED on request timeouts;
Added support of onloadend handler if available instead of onreadystatechange;
Added xhr timeout test;
Fixed potential bug of xhr adapter with proper handling timeouts&errors (FakeXMLHTTPRequest failed to handle timeouts);

* Removed unnecessary assertion;
@jasonsaayman
Copy link
Member

Fixed with #3688

mbargiel pushed a commit to mbargiel/axios that referenced this issue Jan 27, 2022
…be passed directly as payload for encoding to JSON axios#2613, axios#61, axios#907 (axios#3688)

* Draft

* Added support for primitive types to be converted to JSON if the request Content-Type is 'application/json';
Added throwing SyntaxError if JSON parsing failed and responseType is json;
Added transitional option object;
Added options validator to assert transitional options;
Added transitional option `silentJSONParsing= true` for backward compatibility;
Updated README.md;
Updated typings;

* Fixed isOlderVersion helper;
Fixed typo;
Added validator.spec.js;

* Added forcedJSONParsing transitional option axios#2791

* `transformData` is now called in the default configuration context if the function context is not specified (for tests compatibility);

* Added `transitional.clarifyTimeoutError` to throw ETIMEDOUT error instead of generic ECONNABORTED on request timeouts;
Added support of onloadend handler if available instead of onreadystatechange;
Added xhr timeout test;
Fixed potential bug of xhr adapter with proper handling timeouts&errors (FakeXMLHTTPRequest failed to handle timeouts);
mbargiel pushed a commit to mbargiel/axios that referenced this issue Jan 27, 2022
* Draft

* Added support for primitive types to be converted to JSON if the request Content-Type is 'application/json';
Added throwing SyntaxError if JSON parsing failed and responseType is json;
Added transitional option object;
Added options validator to assert transitional options;
Added transitional option `silentJSONParsing= true` for backward compatibility;
Updated README.md;
Updated typings;

* Fixed isOlderVersion helper;
Fixed typo;
Added validator.spec.js;

* Added forcedJSONParsing transitional option axios#2791

* `transformData` is now called in the default configuration context if the function context is not specified (for tests compatibility);

* Added `transitional.clarifyTimeoutError` to throw ETIMEDOUT error instead of generic ECONNABORTED on request timeouts;
Added support of onloadend handler if available instead of onreadystatechange;
Added xhr timeout test;
Fixed potential bug of xhr adapter with proper handling timeouts&errors (FakeXMLHTTPRequest failed to handle timeouts);

* Removed unnecessary assertion;
@KaKi87
Copy link

KaKi87 commented Jul 3, 2022

Hello,

Fixed with #3688

@jasonsaayman Are you talking about OP's issue ?
Because I'm still experiencing it in v0.27.2 and forced to use @liesauer's workaround.

Thanks

@yozachar
Copy link

yozachar commented Jul 13, 2023

Hi, is this behaviour expected?

// standard
import fs from "fs";
import path from "path";

// external
import axios, { AxiosError } from "axios";

async function request() {
  const url = "https://api.github.com";
  const localFileName = path.join(__dirname, "response.txt");

  try {
    const response = await axios.get(url, {
      responseType: "text",
      transformResponse: [(data) => data],
    });
    fs.writeFile(localFileName, response.data, (fsError) => {
      if (fsError) {
        throw fsError;
      }
    });
  } catch (error) {
    if (error instanceof AxiosError) {
      console.error(error.response.status, error.response.statusText);
    } else {
      console.error(error);
    }
    return null;
  }
}

request();

JSON data gets written to a text file. I want to accept only files like at https://www.gnu.org/licenses/gpl-3.0.txt

@liesauer workaround doesn't seem to work.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

8 participants