为了账号安全,请及时绑定邮箱和手机立即绑定

使用 fetch API 与 PHP 的 CORS “SyntaxError: Unexpected

使用 fetch API 与 PHP 的 CORS “SyntaxError: Unexpected

PHP
万千封印 2022-07-22 18:29:30
/** @version: 1.0.0* @author: Murod Parmonov* @licence: MIT*/class HTTP{    // post request    post(url, data){        return new Promise((resolve, reject) => {                fetch(url, {                    method: 'POST',                    headers: {                        'Content-type': 'application/json'                    },                    body: JSON.stringify(data),                    'mode': 'no-cors'                }).                **then(response => response.json()).then(data => resolve(data)).                catch(err => reject(err));**            }        );    }}const ht = new HTTP;  // http  fetch API classht.post('https://correctserverurl.com/', data).then(resData => console.log(resData))    .catch(err => console.log(err));我从服务器得到的错误 ,js 代码中用双星标记的行是行错误。<?phpheader('Access-Control-Allow-Origin: correctdomain.com');header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");header("Access-Control-Allow-Headers:  X-Requested-With");$ping = file_get_contents("php://input");file_put_contents('ping.json', $ping);$ping = json_decode($ping, 1);echo json_encode($data = [    'status' => 'success']);我包括了整个类的 fetch API,即使我认为它是不必要的。我想我提供了所需的每一个细节。我确保代码可以在其他服务器上运行,但仅在我的服务器上出现问题。我在这里做错了什么?我应该怎么做才能解决这个问题?
查看完整描述

1 回答

?
qq_花开花谢_0

TA贡献1835条经验 获得超7个赞

header('Access-Control-Allow-Headers: X-PINGOTHER, Content-Type'); 实际上,这值得做一点研究。魔术线帮助我解决了同样的问题。



查看完整回答
反对 回复 2022-07-22
  • 1 回答
  • 0 关注
  • 228 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号