当前位置: 首页 > 知识库问答 >
问题:

WordPress REST API返回401通过Axios发布时未授权

万俟渊
2023-03-14

我试图通过我的Vue/Nuxt应用程序使用Axios和JWT将表单中的数据发布到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 );
    });
});

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

使现代化

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

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

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

我已经修改了我的代码,使用wait/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发出请求

在错误文档中,我注意到with凭据被设置为false,尽管它在配置中被设置为true。为什么会这样?

共有1个答案

祁星阑
2023-03-14

试试这个

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

点击这个链接

 类似资料:
  • 所以,我试图用Tweepy喜欢一个推文,但是这个错误正在发生: 有什么想法吗?

  • 我的数据未发布在postman api中,这会导致以下错误: 单调的节奏。我的主人。com/api/领域:1个职位http://dradiobeats.x10host.com/api/areas401(未授权)核心。js:4002错误HttpErrorResponse 我的app.component.ts 如何解决此错误?

  • 我正在使用postman,并尝试通过http://localhost:8180/auth/admin/realms/demo/users/{userID}更新用户的配置文件,但收到响应。 通过http://localhost:8180/auth/admin/realms/demo/users/{userID}发送带有Json内容类型和用户信息的Put请求。 不幸的是,我已经连续收到了401个回复。

  • 我正在尝试使用Python脚本和Tweepy API阻止Twitter用户。我能够毫无问题地提取用户、ID、追随者和推文。当我尝试调用

  • 为了发送和检索信封,我正在将我的应用编程接口后端与文档签名集成。我正在使用JWT Grant流。认证选项 在DocuSign开发环境中,我能够使用JWT流和DocuSign C#SKD检索访问令牌。然后我需要调用endpoint,以检索用于调用Docusign的基本uri字段。 当我提出GET请求时https://account-d.docusign.com/oauth/userinfo,包括授权

  • 在这个留档Spring Security MVC Test中描述了如何使用Spring Security测试安全的ressource。我遵循了提供的所有步骤,但访问受保护的ressource仍然会返回错误代码401(未经授权)。 这是我的测试课 我的资源服务器配置: 如果你想看看整个项目,你可以在这里找到。我已经尝试了不同的测试运行程序和教程中描述的所有内容,但我找不到一个解决方案,如何在测试期间