我正在尝试使用Axios和JWT通过我的Vue / Nuxt应用程序将表单中的数据发布到WordPress REST API。
我能够获得有效的令牌并将其保存为cookie,但是当我尝试将数据发布到API时,我收到401 Unauthorized错误消息“rest_cannot_create” - 抱歉,您不能以此用户身份发布。
有问题的用户是JWT授权的用户。我已经尝试过它们作为作者(创建和编辑自己的帖子)和编辑器(可以创建,编辑和删除自己的帖子),但两者都有相同的结果。
我的代码如下:
submitForm: function() {
let formData = {
type: 'kic_enquiries',
title: {
rendered: 'Enquiry from ' + this.firstname + ' ' + this.lastname + ' [' + new Date() + ']'
},
acf: {
enquiry_name: this.firstname + ' ' + this.lastname,
enquiry_email: this.emailaddress,
enquiry_phone: this.phonenumber,
enquiry_message: this.message
}
};
this.formSubmission.push(formData);
const bodyFormData = new FormData();
bodyFormData.set('username', 'username');
bodyFormData.set('password', 'password');
axios ({
method: 'post',
url: url + '/wp-json/jwt-auth/v1/token',
data: bodyFormData,
config: {
headers: { 'Content-Type': 'multipart/form-data' }
}
})
.then(res => {
this.$cookies.set("cookiename", res.data.token, "3MIN");
}).catch(function(error) {
console.error( 'Error', error );
}).finally(() => {
console.log('Posting form...');
axios ({
method: 'post',
url: url + '/wp-json/wp/v2/kic-enquiries',
data: JSON.stringify(this.formSubmission),
config: {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization:': 'Bearer ' + this.$cookies.get("cookiename")
}
}
})
.then(submitResponse => {
console.log('Form submitted...' + submitResponse)
return submitResponse;
}).catch(function(error) {
console.error( 'Error', error );
});
});
我需要使用拦截器吗?我在网上看到了很多关于他们的信息,但我找不到任何可以解释我如何在我的情况下使用它们的内容。
UPDATE
进一步的调查显示,当通过邮递员发送与应用程序相同的设置和数据时,令牌有效,因此它似乎是一个代码问题。
帖子失败了因为我错误地发送了令牌吗?
2019年2月2日至15日
我已修改我的代码以使用await / async和watcher来检查要生成的令牌,但我仍然收到401错误。更新后的代码如下:
<script>
import axios from 'axios'
export default {
data: function() {
return {
firstname: null,
lastname: null,
emailaddress: null,
phonenumber: null,
message: null,
formSubmission: [],
res: [],
authStatus: false,
token: null
}
},
methods: {
submitForm: async function() {
let formData = {
type: 'kic_enquiries',
title: {
rendered: 'Enquiry from ' + this.firstname + ' ' + this.lastname + ' [' + new Date() + ']'
},
acf: {
enquiry_name: this.firstname + ' ' + this.lastname,
enquiry_email: this.emailaddress,
enquiry_phone: this.phonenumber,
enquiry_message: this.message
},
status: 'draft'
};
this.formSubmission.push(formData);
console.log(JSON.stringify(this.formSubmission));
await this.getToken();
},
getToken: function() {
console.info('Getting token...');
const bodyFormData = new FormData();
bodyFormData.set('username', 'user');
bodyFormData.set('password', 'pass');
axios ({
method: 'post',
url: link,
data: bodyFormData,
config: {
withCredentials: true,
headers: { 'Content-Type': 'multipart/form-data' },
}
})
.then(res => {
this.$cookies.set("XSRF-TOKEN", res.data.token, "30MIN");
console.log('Cookie:' + this.$cookies.get("XSRF-TOKEN"));
}).catch(function(error) {
console.error( 'Error', error );
}).finally(() => {
this.authStatus = true;
this.token = this.$cookies.get("XSRF-TOKEN");
});
}
},
watch: {
authStatus: function() {
if (this.authStatus == true) {
console.info('Posting form...');
axios ({
method: 'post',
url: 'link,
data: this.formSubmission,
config: {
withCredentials: true,
headers: {
'Authorization:': 'Bearer ' + this.token
}
}
})
.then(submitResponse => {
console.log('Form submitted...' + submitResponse)
return submitResponse;
}).catch(function(error) {
console.error( 'Error', error );
});
}
else {
console.error('Token not generated')
}
}
}
}
</script>
所以现在,表单提交必须等待在尝试向API发出请求之前生成并应用令牌。
在错误文档中我注意到withCredentials
被设置为false
,即使它在配置中设置为true
。那为什么会这样?
**Try this**
let headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + 'Authorization:': 'Bearer ' + this.token
}
this.axios.post('link', JSON.stringify(this.formSubmission), {
headers: headers})