【问题标题】:WordPress REST API returns 401 Unauthorized when posting via Axios & valid JWT通过 Axios 和有效 JWT 发布时,WordPress REST API 返回 401 Unauthorized
【发布时间】:2019-06-17 21:04:01
【问题描述】:

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

我能够获取有效令牌并将其保存为 cookie,但是当我尝试将数据发布到 API 时,我收到 401 Unauthorized 错误消息 "rest_cannot_create" - 抱歉您不能以该用户的身份发帖

相关用户是智威汤逊授权的用户。作为作者(创建和编辑他们自己的帖子)和编辑者(可以创建、编辑和删除他们自己的帖子),我已经尝试过,但两者的结果相同。

我的代码如下:

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

我需要使用拦截器吗?我在网上看到了很多关于它们的信息,但我找不到任何解释我需要如何根据我的情况使用它们的信息。

更新

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

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

2019 年 2 月 2 日至 15 日更新

我已修改我的代码以使用 await/async 和一个观察程序来检查要生成的令牌,但我仍然收到 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。为什么会这样?

【问题讨论】:

  • 这可能是CORS 的问题吗?
  • 实际上,您可能是对的。端点的标头只允许 GET...我将进一步研究。
  • 如果您发现 CORS 问题,请将其作为答案发布并附上说明
  • 不幸的是,安装插件后我仍然遇到同样的错误。

标签: vue.js jwt axios nuxt.js wordpress-rest-api


【解决方案1】:

试试这个

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

关注这个link

【讨论】:

  • 谢谢@Saroj,您能否解释一下为什么这有助于解决问题?
  • 为了传递自定义标头,提供一个包含标头的对象作为最后一个参数。我遇到了同样的问题,我就这样解决了。
  • 酷,我试试看!
猜你喜欢
  • 2015-03-13
  • 2018-11-06
  • 2022-06-10
  • 2021-10-11
  • 2020-06-11
  • 2018-04-28
  • 2021-08-03
  • 2021-05-14
  • 2017-01-25
相关资源
最近更新 更多