Housefly
Housefly

Reputation: 4422

Get api working in Postman but not with Axios

I am following a tutorial from Udemy and got stuck here:

Yelp.js

import axios from "axios";

export default axios.create({
    baseURL : 'https://api.yelp.com/v3/businesses',
    headers : {
        Authorization : 
        'Bearer ****************'
    }
})

SearchScreen.js

const SearchScreen = () => {

    const [term, setTerm] = useState('');
    const [results, setResults] = useState([]);

    const searchApi = async () => {
        const response = await yelp.get('', {
            params : {
                term : term,
                location: 'san jose'
            }
        });
        setResults(response.data);
    }

    return (
        <View style={styles.backgroundStyle}>
            <SearchBar 
                term = {term} 
                onTermChange = {setTerm}
                onTermSubmit = {searchApi} />

            <Text>We have found {results.length} results</Text>
        </View>
    );
};

const styles = StyleSheet.create({
    backgroundStyle : {
        backgroundColor : '#FFFFFF',
        flex: 1
    }
})

export default SearchScreen

When searchApi is triggered I see this error in the console

[Unhandled promise rejection: Error: Network Error]
at node_modules/axios/lib/core/createError.js:15:17 in createError
at node_modules/axios/lib/adapters/xhr.js:114:22 in handleError
at node_modules/react-native/Libraries/Network/XMLHttpRequest.js:609:10 in setReadyState
at node_modules/react-native/Libraries/Network/XMLHttpRequest.js:396:6 in __didCompleteResponse
at node_modules/react-native/Libraries/vendor/emitter/_EventEmitter.js:135:10 in EventEmitter#emit

The same Api with the same Authorization key is working in Postman. Am I missing something here?

Upvotes: 1

Views: 18569

Answers (7)

I.sh.
I.sh.

Reputation: 1983

I've found that the best way to compare your Axios request to Postman request is via Postman console.

In the console you can see (hidden) proxy settings, hidden headers, and other network info.

enter image description here

Upvotes: 0

Himanshu Joshi
Himanshu Joshi

Reputation: 126

You might be missing one of them in header

  1. cookie
  2. Some custom header which server expect
  3. origin
  4. user-agent Might be serving added it as security purpose

Upvotes: 0

Thomas Easo
Thomas Easo

Reputation: 3758

@housefly

I think the difference between a postman GET request and your axios request is due to the hidden headers. Postman has internal logic to append the request type and below headers even if your didn't mention. Where as your manual query using Axios is not having sufficient header. Could you please try the below headers in your axios API call.

Post Man API which contains all headers

Upvotes: 2

Yogesh Chauhan
Yogesh Chauhan

Reputation: 151

check the XHR request in the network tab by the active developer tool. If you are getting errors in your API. If you are getting the response correct then debug your code by catching the exception.

Upvotes: 0

Ariel Perez
Ariel Perez

Reputation: 519

If the connection is not the issue, the error is on the request and maybe the API is trying to let you know the error code but you aren't capturing it.

Implement a try/catch like this:

try {
  const response = await yelp.get('', {
    params : {
        term : term,
        location: 'san jose'
    }
  });
  setResults(response.data); 
} catch (ex) {
  if (ex && ex !== undefined && ex.toString && ex.toString !== undefined) {
    // print the general exception
    console.log(ex.toString());
  }     
  if (
    ex.response &&
    ex.response !== undefined &&
    ex.response.data &&
    ex.response.data !== undefined
  ) {
    // print the exception message from axios response
    console.log(ex.response.data);
  }
}

Then check your console.

Upvotes: 2

Code
Code

Reputation: 6251

It's likely a CORS error. See Calling Yelp API from frontend JavaScript code running in a browser

That code cannot be ran from a browser, which has CORS protection. If you have to, you can try to disable CORS using a third party browser extension or otherwise. (At your own risk!)

Upvotes: 1

Suneet Jain
Suneet Jain

Reputation: 256

You need to catch the error using try catch block. If you are not getting any error then you can also check the network XHR calls in developer panel of your web browser. In the developer panel you can exactly see the API call url, headers and body as well you can see the response received from the API.

Chrome Browser -> https://developer.chrome.com/docs/devtools/open/

Firefox -> https://developer.mozilla.org/en-US/docs/Tools/Web_Console

If you need further help then feel free to post the screenshot from your network panel or push your code to github to debug further.

Upvotes: 1

Related Questions