提取不适用于反应ComponentDidMount

时间:2020-05-01 09:39:10

标签: reactjs

如标题所示,以下内容无效:

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;

在浏览器中,我总是看到“你好”,在检查器中,我看到对http://localhost:8080/EntityType的GET请求成功,并带有有效的json响应,

出什么问题了?

更新:当我在开发人员控制台中执行提取操作时,firefox记录了日志:

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).

1 个答案:

答案 0 :(得分:0)

这是一个CORS问题。

我在我的spring Controller方法中添加了@CrossOrigin(origins = "http://localhost:3000"),问题得以解决。