在进行API调用时获得以下500代码响应:PUT https://my-site.com/wp/wp-json/contact/v1/send 500
在functions.php
中,我的WP自定义路由是这样定义的:
function sendContactMail(WP_REST_Request $request) {
}
add_action('rest_api_init', function () {
register_rest_route( 'contact/v1', 'send', array(
'methods' => 'PUT',
'callback' => 'sendContactMail'
));
});
以下是我如何进行API调用:
formData.append('contact_name', this.contactName)
formData.append('contact_email', this.contactEmail)
formData.append('contact_message', this.contactMessage)
this.$axios.$put('https://my-site.com/wp/wp-json/contact/v1/send', formData)
.then((res) => {
this.ApiResponse = res
})
.catch((err) => {
this.$toast.error(err.response)
})
为什么我会出错500?
问题可能是回调函数需要return
值。在function sendContactMail(WP_REST_Request $request) { }
结束时,您需要返回一个WP_REST_Response
或WP_Error
以发送回响应。
我在这里设置了一个快速的小示例:https://xhynk.com/content-mask/65451758-answer/
";点击我(坏(";以及";点击我(好(";按钮的作用完全相同,只是更改正在发送的数据。sendContactMail()
函数的唯一区别如下:
function sendContactMail(WP_REST_Request $request) {
if( $request->get_body() == 'return=true' ){
return new WP_REST_Response(
array(
'status' => 200,
'response' => 'Did the thing'
);
);
}
}
";真";条件仅在";好的"按钮,这是处理.done()
块的地方,与";坏的"按钮触发.catch
块。
因此,你应该能够解决你的问题,通过对你的数据进行X、Y、Z操作,并确保你返回了正确的响应
还要确保您没有遇到PHP错误(比如直接访问$request
属性,因为它们是protected
属性,而执行类似if( $request->body == 'something' )
的操作将触发"PHP致命错误:无法访问受保护的属性">并出现500错误。
更新类似的功能
function sendContactMail(WP_REST_Request $request) {
}
add_action('rest_api_init', function () {
register_rest_route( 'contact/v1', '/send', array(
'methods' => 'PUT',
'callback' => 'sendContactMail'
));
});
更新类似的功能
formData.append('contact_name', this.contactName)
formData.append('contact_email', this.contactEmail)
formData.append('contact_message', this.contactMessage)
this.$axios.$put('https://my-site.com/wp-json/contact/v1/send', formData)
.then((res) => {
this.ApiResponse = res
})
.catch((err) => {
this.$toast.error(err.response)
})
Bug在进行API调用JS脚本
中,因此,从URL中删除额外的wpttps://my-site.com/wp-json/contact/v1/send
更新后的脚本将如下所示
formData.append('contact_name', this.contactName)
formData.append('contact_email', this.contactEmail)
formData.append('contact_message', this.contactMessage)
this.$axios.$put('https://my-site.com/wp-json/contact/v1/send', formData)
.then((res) => {
this.ApiResponse = res
})
.catch((err) => {
this.$toast.error(err.response)
});