简体   繁体   中英

fetch does not work in react ComponentDidMount

as the titles say, the following does not work:

import React, { Component } from 'react'

class MDComponent extends Component{
    constructor(props){
        super(props);
        this.state = {contacts: []};
    }
    componentDidMount() {
        fetch('http://localhost:8080/EntityType',  {
            headers:{
                "Accept": "application/json",
            }
        })
            .then((res) => {return res.json()})
            .then(data =>
            {this.setState({ contacts: data.toString() })})
            ;
    }



    render() {
        return(
            <div> hello {this.state.contacts}</div>
        )
    }
}

export default MDComponent;

in browsers I always see "hello", in inspector I see a successful GET request to the http://localhost:8080/EntityType with a valid json response,

what is the problem?

update: logs from firefox when I execute a fetch in its developer consol:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8080/EntityType. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

It was a CORS problem.

I added @CrossOrigin(origins = "http://localhost:3000") to my spring Controller method, and the problem solved.

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