繁体   English   中英

ReactJs componentDidMount fetch url 覆盖表单提交 fetch url

[英]ReactJs componentDidMount fetch url overwriting form submit fetch url

在我的组件中,它从一个 componentDidMount() 生命周期开始,该生命周期获取数据以显示在表格上。

componentDidMount() {
        fetch(TABLE_DATA, { 
        //TABLE_DATA is a global variable that runs a callback which combines the rest of the variable
        //to the url. It's mostly for deployment; an easy way to change urls back and forth. 
            credentials: 'include',
            methods: 'GET',
            headers: {
                'Content-type': 'application/json',
            },
        })
        .then(res => res.json())
        .then(data=>{
            this.setState({
                tableData: data,
                isLoaded: true
            })
        })
   }

现在,当我想在同一组件中的表单上提交一些信息时,出于某种原因,TABLE_DATA 变量会覆盖我正在获取的任何 url。 以下是提交表单的代码:

    submitAccountToUser= e => {
        e.preventDefault()
        fetch(EXTRA_INFO, {
            credentials: 'include',
            methods: 'POST',
            headers: {'Content-type': 'application/json'},
            body: JSON.stringify({
                'info':this.state.info
            })
        })
        .then(res => console.log('res', res)) 
        //doesn't get to this console.log. It stops on the line with "fetch(EXTRA_INFO
    }

EXTRA_INFO 被覆盖为 TABLE_DATA。 它在我的本地服务器/终端上显示在 TABLE_DATA url 处调用了一个“GET”方法。 除了我的浏览器中的这个错误:

未处理的拒绝(TypeError):无法在“窗口”上执行“获取”:使用 GET/HEAD 方法的请求不能有正文。

这是有道理的,因为最初的 fetch 调用 (TABLE_DATA) 只是一个“GET”请求,不能有正文。 但它甚至不应该为 url 获取。 我通过查找语法错误并检查全局变量中的 url 来保持简单。 但我不明白为什么它会完全忽略 EXTRA_INFO 的价值。

**编辑** TABLE_DATA 和 EXTRA_INFO 从中获取其 api 的回调 function 如下所示:

const TABLE_DATA = backend_route('/tableinfo')

const backend_route = (route) => {
    const backend = 'http://127.0.0.1:5000'
    return backend + route
}

问题出在我的提交获取方法上。 我有'methods' ,而不是'method'

傻我。 但我发现 react 对那个错误的反应很奇怪

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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