Vue.js WordPress REST API在通过Axios&;发布时返回401未经授权;有效JWT

Vue.js WordPress REST API在通过Axios&;发布时返回401未经授权;有效JWT,vue.js,jwt,axios,nuxt.js,wordpress-rest-api,Vue.js,Jwt,Axios,Nuxt.js,Wordpress Rest Api,我正在尝试使用Axios和JWT通过Vue/Nuxt应用程序将表单中的数据发布到WordPress REST API 我可以获取有效令牌并将其保存为cookie,但当我尝试将数据发布到API时,我收到一个401未经授权的错误,消息为“rest\u cannot\u create”-很抱歉,不允许您以此用户身份发布 所涉及的用户是JWT授权的用户。我曾以作者(创建和编辑他们自己的帖子)和编辑(可以创建、编辑和删除他们自己的帖子)的身份尝试过,但两者的结果都是一样的 我的代码如下: submitFo

我正在尝试使用Axios和JWT通过Vue/Nuxt应用程序将表单中的数据发布到WordPress REST API

我可以获取有效令牌并将其保存为cookie,但当我尝试将数据发布到API时,我收到一个401未经授权的错误,消息为“rest\u cannot\u 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 );
    });
});
<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>
我需要使用拦截器吗?我在网上看到了很多关于它们的信息,但是我找不到任何东西来解释我需要如何在我的情况下使用它们

更新

进一步的调查显示,当通过邮递员使用与应用程序相同的设置和数据发送令牌时,令牌可以正常工作,因此这似乎是一个代码问题

帖子失败是因为我错误地发送了令牌吗

更新日期:2019年2月2日至15日

我已经修改了我的代码,使用wait/async和一个watcher来检查要生成的令牌,但是我仍然得到了401错误。更新代码如下:

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 );
    });
});
<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>

从“axios”导入axios
导出默认值{
数据:函数(){
返回{
名字:空,
姓氏:空,
电子邮件地址:空,
电话号码:空,
消息:空,
提交表格:[],
决议:[],
authStatus:false,
令牌:空
}
},
方法:{
submitForm:async函数(){
设formData={
键入:“kic_查询”,
标题:{
呈现:“来自'+this.firstname+''+this.lastname+'['+新日期()+']的查询”
},
acf:{
查询名称:this.firstname+“”+this.lastname,
查询电子邮件:this.emailaddress,
查询电话:这个电话号码,
查询信息:this.message
},
状态:“草稿”
};
此.formSubmission.push(formData);
log(JSON.stringify(this.formSubmission));
等待这个;
},
getToken:function(){
console.info('获取令牌…');
const bodyFormData=新FormData();
bodyFormData.set('username','user');
设置('password','pass');
axios({
方法:“post”,
网址:link,
数据:bodyFormData,
配置:{
事实上,
标题:{“内容类型”:“多部分/表单数据”},
}
})
。然后(res=>{
该.$cookies.set(“XSRF-TOKEN”,res.data.TOKEN,“30分钟”);
log('Cookie:'+this.$cookies.get(“XSRF-TOKEN”);
}).catch(函数(错误){
控制台错误('error',error);
}).最后(()=>{
this.authStatus=true;
this.token=this.cookies.get(“XSRF-token”);
});
}
},
观察:{
authStatus:function(){
if(this.authStatus==true){
console.info('Posting form…');
axios({
方法:“post”,
url:'链接,
数据:此.formSubmission,
配置:{
事实上,
标题:{
“授权:”:“持有人”+此令牌
}
}
})
.然后(提交响应=>{
console.log('formsubmitted…'+submitResponse)
返回次响应;
}).catch(函数(错误){
控制台错误('error',error);
});
}
否则{
console.error('未生成令牌')
}
}
}
}
因此,表单提交必须等待生成并应用令牌,然后才能尝试向API发出请求

在错误文档中,我注意到,
withCredentials
被设置为
false
,即使它在配置中被设置为
true
。为什么会这样?

试试这个

let headers = {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer ' + 'Authorization:': 'Bearer ' + this.token
}
this.axios.post('link', JSON.stringify(this.formSubmission), {headers: headers})

遵循这个

这可能是个问题吗?事实上,你可能是对的。端点的标头仅允许获取。。。我将对此进行进一步研究。如果您发现CORS问题,请将其作为一个带有解释的答案发布。不幸的是,我在安装插件时仍然会遇到相同的错误。感谢@Saroj,您能否解释一下为什么这有助于解决问题?为了传递自定义标题,请提供一个包含标题的对象作为最后一个参数。我也面临着同样的问题,我就是这样解决的。酷,我要试试!