如何从React组件向后端发送提取请求请求

时间:2019-01-12 18:18:05

标签: reactjs fetch-api

enter image description here

我想将获取后请求从react类组件发送到服务器。我从没拿过帖子。因此,我该如何使用thunk从该组件执行此操作。

class Add extends Component {
	constructor(props) {
		super(props);
		this.state = {username: '', email:'', text:''};
		this.handleChange = this.handleChange.bind(this);
		this.handleSubmit = this.handleSubmit.bind(this);
	}
	handleChange(event) {
		this.setState({value: event.target.value});
	}
	
	handleSubmit(event) { 
                alert (JSON.stringify(this.state))
		event.preventDefault();
	}
	render(){
		return (
		<div className="addcontainer">
		<div style={{display: 'flex', justifyContent: 'center'}}>
		<h4>Add new task here:</h4>
		</div>
		<form onSubmit={this.handleSubmit}>
		<div className="wrapper">
			<label for="username"><b>Username</b></label>
			<input type="text" value={this.state.username} onChange={e => this.setState({ username: e.target.value })} placeholder="Enter Username" name="uname" required />
			<label for="email"><b>Email</b></label>
			<input type="text" value={this.state.password} onChange={e => this.setState({ email: e.target.value })} placeholder="Enter Email" name="email" required />
			<label for="text"><b>Text</b></label>
			<input type="text" value={this.state.password} onChange={e => this.setState({ text: e.target.value })} placeholder="Enter Task" name="text" required />
			<button className="login" type="submit">Add task</button>	
		</div>
		</form>
		</div>
		)
	}
}

我在文档中也有一个有关jquery ajax请求的示例,但这对我没有多大帮助。请帮我用fetch写thunk

  $(document).ready(function() {
    var form = new FormData();
    form.append("username", "Example");
    form.append("email", "example@example.com");
    form.append("text", "Some text");

    $.ajax({
        url: 'https://uxcandy.com/~shapoval/test-task-backend/create?developer=Example',
        crossDomain: true,
        method: 'POST',
        mimeType: "multipart/form-data",
        contentType: false,
        processData: false,
        data: form,
        dataType: "json",
        success: function(data) {
            console.log(data);
        }
    });
});  

这是可与fetch get一起使用的thunk:

const getRepos = username => async dispatch => {
  try {
    var url = `https://uxcandy.com/~shapoval/test-task-backend/?developer=sait&sort_field=${username}`;
    const response = await fetch(url);
    const responseBody = await response.json();
    //console.log(responseBody.message.tasks);
    dispatch(addRepos(responseBody.message.tasks));
  } catch (error) {
    console.error(error);
    dispatch(clearRepos());
  }
};

1 个答案:

答案 0 :(得分:1)

您可以使用访存函数的第二个参数添加options,例如

fetch(url, {
    method: "POST", // *GET, POST, PUT, DELETE, etc.
    mode: "cors", // no-cors, cors, *same-origin
    cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
    credentials: "same-origin", // include, *same-origin, omit
    headers: {
        "Content-Type": "application/json",
        // "Content-Type": "application/x-www-form-urlencoded",
    },
    redirect: "follow", // manual, *follow, error
    referrer: "no-referrer", // no-referrer, *client
    body: JSON.stringify(data), // body data type must match "Content-Type" header
})

有关更多信息,请参阅here

使api生效的另一种有效方法是使用axios