【发布时间】:2018-05-19 14:14:21
【问题描述】:
我在通过它的 REST API 将图像上传到 Wordpress 时遇到了一个(看似简单的)问题。现在的情况是这样的:
- 我目前正在我的机器上进行本地开发,因此我正在使用 MAMP 运行 Wordpress。
- 我在应用程序的前端使用 React,并使用 Wordpress REST API 作为后端;所以我现在正在运行一个无头 CMS 应用。
- 使用 Postman,我可以将图像上传到 Wordpress。我可以转到 Wordpress 管理面板并在仪表板中查看实际存在的图像。我也进行了身份验证,我在我的应用程序上都登录了,并且 JWT 令牌与 Postman 的标头一起传递。
问题:我正在使用 Axios 发出与 Postman 相同的 Post 请求,但我收到某种 CORS 错误,我不确定如何在WordPress 后端。
这是来自我的浏览器控制台的确切错误:
无法加载http://localhost:8888/wp-json/wp/v2/media:请求标头字段缓存控制不允许 预检响应中的 Access-Control-Allow-Headers。
我的 AJAX 调用(这是在 React 中并使用 Axios)
onFileChange(event) {
let files = event.target.files || event.dataTransfer.files;
if (!files.length) {
console.log('no files');
} else {
axios.post('http://localhost:8888/wp-json/wp/v2/media', files, {
headers: {
'content-type': 'image/png',
'content-disposition': 'attachment; filename=testImageNum2.png',
'Authorization': `Bearer ${localStorage.getItem('token')}`,
'cache-control': 'no-cache',
}
})
}
}
render() {
return (
<div>
<Header />
<h2>Upload A File Here:</h2>
<input id="file_selector" type="file" name="file" onChange={this.onFileChange} />
</div>
)
}
目前,WP REST API 似乎没有太多关于这个主题的信息。如果有人可以帮助阐明这个话题,我将非常感激!
【问题讨论】:
标签: php wordpress reactjs axios wordpress-rest-api