我正在尝试向rest api发出POST请求。但我正在401 Unauthorised error
. 还有人能帮助处理其中的临时事件吗?
#OurPostData:包含标题。
fetch(\'https://mywebsite.online/wp-json/wp/v2/code\',{
method: \'POST\',
credentials: \'same-origin\',
headers: new Headers({\'Content-Type\': \'application/x-www-form-urlencoded\'}),
body:JSON.stringify(OurPostData),
}).then(response => {
console.log(response);
return response.json();
});
以下方法有效
var createPost = new XMLHttpRequest();
createPost.open("POST", "https://mywebsite.online/wp-json/wp/v2/code");
createPost.setRequestHeader("X-WP-Nonce", Ajax.nonce);
createPost.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
createPost.send(JSON.stringify(OurPostData));
createPost.onreadystatechange = function() {
if (createPost.readyState == 4) {
if (createPost.status == 201) {
alert("Success");
} else {
alert("Error Try Again");
}
}
}
谢谢
最合适的回答,由SO网友:Alt C 整理而成
\'X-WP-Nonce\' : Ajax.nonce
丢失了这就是为什么它会出错
fetch(\'https://mywebsite.online/wp-json/wp/v2/code\', {
method: \'POST\',
credentials: \'same-origin\',
headers: new Headers({
\'Content-Type\': \'application/json;charset=UTF-8\',
\'X-WP-Nonce\' : Ajax.nonce
}),
body: JSON.stringify(OurPostData),
}).then(response => {
console.log(response);
return response.json();
});