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

ตอบกระทู้

รูปแสดงอารมณ์
:icon_plusone: :like: :plusone: :gfb: :-D :) :( :-o 8O :? 8) :lol: :x :P :oops: :cry: :evil: :twisted: :roll: :wink: :!: :?: :idea: :arrow: :| :mrgreen: :angry: :baa: :biggrin:
รูปแสดงอารมณ์อื่นๆ

BBCode เปิด
[img] เปิด
[url] เปิด
[Smile icon] เปิด

กระทู้แนะนำ
   

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

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

โดย thatsawan » 13/06/2016 9:43 pm

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

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

       $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 ด้วย

ข้างบน