我使用reactjs通过API发表评论。当我使用Postman时,它工作良好,但在reactjs上,它不工作。你可以检查我的代码吗?
export function createComment(data) {
console.log(data);
var token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9sb2NhbGhvc3RcL3N5bXBsZSIsImlhdCI6MTU0MzI5MTYyMSwibmJmIjoxNTQzMjkxNjIxLCJleHAiOjE1NDM4OTY0MjEsImRhdGEiOnsidXNlciI6eyJpZCI6IjIifX19.PAtLgv_AZ4sdLhuqirIg1HMidkFxYwNe7t1yr4MMspM";
return fetch('http://localhost/website/wp-json/wp/v2/comments', {
method: 'POST',
body: JSON.stringify(data),
"headers": {
'Authorization': 'Bearer '+token,
'Content-Type': 'application/json'
}
}).then(res => {
return res;
}).catch(err => err);
}
控制台上的问题是:401 (Unauthorized)
,
console.log(data)仍然有效:
{author_name: "ha", author_email: "blabla@gmail.com", author_url: "https://google.com", content: "31231231232131", post: 65, …}
下面是postMan的代码:
var request = require("request");
var options = { method: 'POST',
url: 'http://localhost/website/wp-json/wp/v2/comments',
qs:
{ author_name: 'babahaha',
author_email: 'ha90@gmail.com',
author_url: 'https://google.com',
content: 'hello',
parent: '0',
post: '65' },
headers:
{ 'Postman-Token': '2b4db31d-b1f5-4c74-b78b-a80cfe9d6d80',
'cache-control': 'no-cache',
Authorization: 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9sb2NhbGhvc3RcL3N5bXBsZSIsImlhdCI6MTU0MzI5MTYyMSwibmJmIjoxNTQzMjkxNjIxLCJleHAiOjE1NDM4OTY0MjEsImRhdGEiOnsidXNlciI6eyJpZCI6IjIifX19.PAtLgv_AZ4sdLhuqirIg1HMidkFxYwNe7t1yr4MMspM' } };
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});
非常感谢您。