AngularJs : วิธีแก้ไข XMLHttpRequest cannot load ส่ง Json มาแแต่ไม่สามารถใช้งานได้ใน ng

jQuery & Ajax Knowledge ความรู้เกี่ยวกับ Javascript , jQuery และ Ajax

Moderator: mindphp, ผู้ดูแลกระดาน

ภาพประจำตัวสมาชิก
thatsawan
PHP VIP Members
PHP VIP Members
โพสต์: 28508
ลงทะเบียนเมื่อ: 31/03/2014 10:02 am
ติดต่อ:

AngularJs : วิธีแก้ไข XMLHttpRequest cannot load ส่ง Json มาแแต่ไม่สามารถใช้งานได้ใน ng

โพสต์ที่ยังไม่ได้อ่าน โดย thatsawan »

ในตัวอย่างการส่งค่า

โค้ด: เลือกทั้งหมด

       $http.post('http://localhost/***/newtopic', {params: topic})
            .success(function (response) {
                   alert(response);
                 
                   if (response == 'success') {
                      $state.go('tab.listview');
                    } else {
                       alert(response);
                 }
              }); 

เเล้วเจอ error

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost/***/newtopic'. (Reason: missing token 'content-type' in CORS header 'Access-Control-Allow-Headers' from CORS preflight channel).


หรือ

XMLHttpRequest cannot load http://localhost/***/newtopic. Request header field Content-Type is not allowed by Access-Control-Allow-Headers in preflight response.



สามารถแก้ไขได้โดย
1. AngularJs : วิธีแก้ไข Cross-Origin Request Blocked ส่ง Json มาแแต่ไม่สามารถใช้งานได้ใน ng
https://www.mindphp.com/forums/viewtopic ... 78&t=34045

2. ปรับวิธีการเขียนส่วนของ Angular (ถ้าแก้ไขด้วยวิธีข้อ 1 ไม่ได้)
- ระบุ dataType
- ระบุ headers
เข้าไปดังตัวอย่าง

โค้ด: เลือกทั้งหมด

  $http({
            method: 'POST',
            url: 'http://localhost/***/newtopic',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'text/plain'
            },
            dataType: "json",
            data: {params: 'topic'}
        }).then(function successCallback(response) {
            console.log(topic);
            // this callback will be called asynchronously
            // when the response is available
        }, function errorCallback(response) {
            // called asynchronously if an error occurs
            // or server returns response with an error status.
        });
เเละให้ทำการเพิ่ม

โค้ด: เลือกทั้งหมด

 $server = $this->request->server('HTTP_ORIGIN', '');
        if (isset($server)) {
            header('Access-Control-Allow-Origin: *');
            header('Access-Control-Allow-Credentials: true');
            header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
        } 
ฝั่งของ php ด้วย
  • Similar Topics
    ตอบกลับ
    แสดง
    โพสต์ล่าสุด

ผู้ใช้งานขณะนี้

สมาชิกกำลังดูบอร์ดนี้: ไม่มีสมาชิกใหม่ และบุคลทั่วไป 28