我一直在尝试使用React进行API调用,我能够成功运行GET和POST请求,但是当我运行PATCH时,它返回400错误,这是错误的请求。但是我能够在邮递员上成功运行相同的请求。
我感觉我没有以正确的格式传递数据,但是正文和标头以与POST方法中相同的格式传递,效果很好。
另外,预检请求也以OK(200)的形式传递,但连接在PATCH请求时关闭
这是我的请求,正在从另一个组件接收ID,然后将其传递到API。
class AddPatients extends React.Component {
constructor(props)
{
super(props);
this.state = {message :''};
console.log(this.props.list_id);
}
addPatients(url)
{
let xhr = new XMLHttpRequest();
xhr.open('PATCH',url, true);
xhr.setRequestHeader("Authorization", "Auth_key");
xhr.setRequestHeader("X-OHP-Developer-API-Key", "API_Key ");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader("Accept", "application/json");
let body = {
data:
[
{
//record 1
},
{
//record 2
}
]
}
const res = xhr.send(JSON.stringify(body));
console.log('the response is', res);
}
onButtonClick()
{
var url = 'the url link/' + this.props.list_id;
this.addPatients(url);
}
render() {
return(
<div>
<button onClick={this.onButtonClick.bind(this)}> Add patients to the list </button>
{this.props.list_id}
</div>
);
}
}
export default AddPatients;
我认为它与OPTIONS请求无关,因为它返回OPTIONS IN Allow-Methods选项,例如:
Request Method: OPTIONS
Status Code: 200 OK
Remote Address: 18.236.241.179:443
Referrer Policy: no-referrer-when-downgrade
HTTP/1.1 200 OK
Date: Tue, 31 Dec 2019 01:03:22 GMT
Server: Apache
Strict-Transport-Security: max-age=63072000; includeSubDomains
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET,POST,HEAD,DELETE,PUT,OPTIONS,PATCH
Access-Control-Allow-Headers: authorization,x-requested-with,x-ohp-developer-api-key,content-type
Vary: Accept-Encoding
Content-Encoding: gzip
Content-Length: 336
Keep-Alive: timeout=15, max=98
Connection: Keep-Alive
Content-Type: text/html; charset=iso-8859-1