简体   繁体   中英

Fetch method returning undefined in React

I am trying to call an API from React but it keeps returning as undefined. This is my code:

import React from 'react';

export default class UserList extends React.Component {
    constructor(props) {
        super(props);
        this.state = { customer: [] };
    }

    componentDidMount() {
        fetch('https://recommenderapi.herokuapp.com/customer_id=x', {
            mode: 'no-cors',
            method: "post",
            headers: {
                "Content-Type": "application/json"
            }
        }).then(({ results }) => this.setState({ customer: results }));
    }

    render() {
        console.log(this.state.customer)
        const customers = this.state.customer.map((item, i) => (
            <div>
                <h1>{item.customer_id}</h1>
                <h1>{item.prediction}</h1>
            </div>
        ));

        return (
            <div id="layout-content" className="layout-content-wrapper">
                <div className="panel-list">{customers}</div>
            </div>
        );
    }
}

This is what the API looks like: 在此处输入图像描述

When I run this, the console.log() returns undefined which then means I get the error TypeError: Cannot read property 'map' of undefined . I am not too sure how to fix this so any help would be appreciated. Thanks.

EDIT: This is what the API returns when you go to the link: {"prediction":["Roam in Rome",""]}

You aren't reading the body of the response and parsing the JSON; instead, you're trying to use a result property on the Response object, which doesn't have one.

To read the body of the response you need to use the methods json() , text() , blob() , and similar. You're probably sending back JSON, so you'd want json() . You also need to check the ok flag first, since if the request fails with a 404 or 500 HTTP error, fetch will fulfill the promise but the result may not be JSON. Finally, you should handle/report errors from fetch :

fetch('https://recommenderapi.herokuapp.com/customer_id=x', {
    mode: 'no-cors',
    method: "post",
    headers: {
        "Content-Type": "application/json"
    }
})
.then(response => {
    // *** Check for HTTP success
    if (!response.ok) {
        throw new Error(`HTTP error ${response.status}`);
    }
    // *** Read the body, parse it as JSON
    return response.json();
})
.then(({ results }) => this.setState({ customer: results }))
.catch(error => {
    // ...*** handle/report error...
});

I think it has to to with mode: "no-cors" that you've specified. MDN documentation says it prevents application/json headers from being sent. Try to change it to "cors"

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