简体   繁体   中英

jQuery ajax call is returning response data as String instead of Object

On the following StackBlitz :

https://stackblitz.com/edit/react-jbthdw?file=src%2FApp.js

I have a code which fetches a JSON data with a list of names.

There are two ways of returning data: Axios and jQuery .

With the Axios approach the code works properly.

Now, because some business decisions I need to replace Axios with jQuery .

My problem is: with jQuery the response.data is fetched as string when it should be as object as it happens with Axios .

Below you have the code, but feel free to play with the StackBlitz playground I provided above:

import React from 'react';
import axios from 'axios';
import $ from 'jquery';
import './style.css';

export default () => {

  const jsonSource = 'https://raw.githubusercontent.com/tlg-265/mockend/master/data.json';
  
  const handleClickAxios = () => {
    axios.get(jsonSource).then(response => {
      console.log({ responseType: (typeof response.data)});
      console.log(response.data);
    });
  };

  const handleClickJQuery = () => {
    sendApiRequest({ url: jsonSource, method: 'get' }).then(response => {
      console.log({ responseType: (typeof response.data)});
      console.log(response.data);
    });
  };

  return (
    <div>
      <h1>Axios vs jQuery</h1>
      <p><b>Inconsitency:</b> returning response as Object vs String</p>
      <button onClick={handleClickAxios}>Axios</button>{' '}
      <button onClick={handleClickJQuery}>jQuery</button>
    </div>
  );
};

export const sendApiRequest = ({
  url,
  method,
  data,
  timeout,
}) => {
  method = method.toUpperCase();

  let additionalSettings = { data: data };
  if (method === 'POST') {
    additionalSettings = {
      contentType: 'application/json',
      dataType: 'json',
      data: JSON.stringify(data),
    };
  }

  return new Promise((resolve, reject) => {
    $.ajax({
      url,
      method: method,
      timeout,
      ...additionalSettings,
      success: (response) => {
        resolve({
          data: response
        });
      },
      error: ({ responseJSON }) => {
        reject(responseJSON);
      },
    });
  });
};

Here you have a screenshot of the issue:

在此处输入图像描述

Any idea on what do I need to update on the code in order to get: response.data as object with jQuery ? I need to get that without any post processing of the response. Is there maybe any params I could use with jQuery so it behaves similarly to Axios ?

Thanks!

The URL you are requesting includes this response header:

 content-type: text/plain; charset=utf-8

Which is why jQuery isn't processing it as JSON automatically.

A quick search of the documentation for the word "json" quickly brings up the dataType option which lets you override the content-type.

 const jsonSource = 'https://raw.githubusercontent.com/tlg-265/mockend/master/data.json'; jQuery.ajax({ url: jsonSource, dataType: 'json' }).then(data => { console.log({ responseType: (typeof data) }); console.log(data); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM