我正在使用React和axios处理表单。以前我使用的是Blade模板(Laravel),现在一切正常,我只是想知道,如果我正在正确地执行POST请求,因为它似乎被忽略了。
这是代码:
import React, { Component } from 'react';
import { render } from 'react-dom';
import axios from 'axios';
export default class Form extends Component {
constructor(props) {
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(e) {
e.preventDefault();
const token = document.querySelector('meta[name="csrf-token"]');
const data = JSON.stringify({
title: this.refs.title.value
})
axios.post('http://127.0.0.1:8000/addpost', data, {
headers: {
'Content-Type': 'application/json',
'X-CSRF-TOKEN': token.content
}
}).then(
response => console.log(response.data)
).catch(
error => console.log(error)
)
}
render() {
return (
<div>
<form onSubmit={this.handleSubmit} method="POST" action="http://127.0.0.1:8000/addpost" acceptCharset="UTF-8">
<input ref="title" name="title" type="text" />
<input type="submit" />
</form>
</div>
)
}
}
我跟进了Laravel文档HTTP Routing,但由于他们使用Ajax,我必须更改代码:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
即使我发出没有标题的帖子请求,数据也会正确存储,这可能不太好。我应该更改帖子请求还是最好的方法?提前谢谢。
答案 0 :(得分:1)
只需尝试以下代码headers
:)
headers: {
'X-Requested-With': 'XMLHttpRequest',
'X-CSRFToken': `Enter CSR Token here`,
}