【问题标题】:Handling the Post request's Response in React JS在 React JS 中处理 Post 请求的响应
【发布时间】:2019-02-02 20:28:18
【问题描述】:

我是个反应迟钝的菜鸟,我正在尝试发出帖子请求并显示回复。这是我发出帖子请求的搜索组件

import React, { Component } from 'react';
import {FormGroup, ControlLabel, FormControl, HelpBlock, Button} from 'react-bootstrap';
import {fieldset} from 'purecss/build/pure.css';
import './layout.css';
import axios from 'axios';

export class Search extends React.Component{
state = {
    Movie :'',
}

handleChange = event =>{
    this.setState({Movie: event.target.value});
}


handleSubmit = event =>{
    event.preventDefault();

    const movie_name = {
        Movie: this.state.Movie
    };

    axios.post(`http://127.0.0.1:7002/get-suggestions`,{movie_name})
    .then(res =>{
        console.log(res);
        console.log(res.data);
    })
};

render(){
    return(
        <div id='layout'>
          <div className="pure-g">
            <div className="pure-u-12-24">
            <form className="pure-form" onSubmit={this.handleSubmit}>
              <fieldset>
              <legend >Enter Movie Name</legend>
                  <input type="text" placeholder="Movie" onChange={this.handleChange}/>
                  <button type="submit" class="pure-button pure-button-primary">Suggest</button>
              </fieldset>
            </form>
            </div>
          </div>
        </div>
    );
}}

我能够成功发出发布请求,但无法获得显示响应,谁能解释一下为什么响应没有被 console.logged 并且响应是一个列表

【问题讨论】:

标签: javascript reactjs post promise axios


【解决方案1】:

正如其他人所提到的,您的服务器应该使用 CORS 正确设置。

如果您无法修改服务器代码,this Chrome extension 是一个很好的临时修复。

【讨论】:

    【解决方案2】:

    这个问题不是关于反应,而是关于CORS(跨域资源共享)。

    您应该向后端 API 添加适当的标头。

    至少Access-Control-Allow-OriginAccess-Control-Allow-Methods

    它可能看起来像这样:

    // indicates that server allows cros-domain requests
    //* - any origin to access the resource,
    // <origin> - certain URI
    setHeader('Access-Control-Allow-Origin', '<origin> or <*>')
    
    // specifies allowed method/methods when accessing the resource
    setHeader('Access-Control-Allow-Methods', 'POST')
    

    【讨论】:

    • 谢谢你?帮助我
    【解决方案3】:

    您的发布请求似乎很好,但在后端请求被阻止。

    所以你必须允许请求。

    res.setHeader('Access-Control-Allow-Origin', '*');
    

    在后端代码中进行这些更改。

    【讨论】:

    • 这不是假设他们在后端使用 Node 吗?
    • 是的,我在 nodejs 服务器中遇到了同样的问题,所以只是共享
    猜你喜欢
    • 2021-11-15
    • 2013-06-19
    • 2015-06-28
    • 1970-01-01
    • 1970-01-01
    • 2021-12-02
    • 1970-01-01
    • 1970-01-01
    • 2021-05-27
    相关资源
    最近更新 更多