جشنواره عیدانه راکت | عضویت ویژه راکت برای آخرین بار | افزایش قیمت‌ها از سال جدید | و ...

مشاهده اطلاعات بیشتر...
ثانیه
دقیقه
ساعت
روز
احسان
3 سال پیش توسط احسان مطرح شد
1 پاسخ

مشکل در ارسال json به api زمان ست کردن contentType

سلام
من قصد دارم درخواست زیر رو به یک api بفرستم:

$.ajax({

        url: 'https://theapi.com/api/verify',
        data: {"mobile":"09123456789"},
        type: 'POST',
        contentType: 'application/json;charset=utf-8',
        dataType: 'json',
        success: function() { alert("Success"); },
        error: function() { alert('Failed!'); },
    });

اما خطای CORS میده. ولی وقتی قسمت زیر رو از کد حذف می‌کنم به سادگی اس ام اس تایید دریافت میشه و اتصال به API به درستی صورت میگیره.

contentType: 'application/json;charset=utf-8',

دلیل و روش رفع مشکل چیه؟ (بدون اینکه اینکه content type حذف بشه)


ثبت پرسش جدید
IrajJavidan
@IrajJavidan1 3 سال پیش مطرح شد
1

https://stackoverflow.com/questions/38998684/cant-send-a-post-request-when-the-content-type-is-set-to-application-json

It turns out that CORS only allows some specific content types.

The only allowed values for the Content-Type header are:

application/x-www-form-urlencoded
multipart/form-data
text/plain
Source: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

To set the content type to be 'application/json', I had to set a custom content type header in the API. Just removed the last header and added this one:
->header('Access-Control-Allow-Headers', 'Content-Type');
and it is working all good.

برای ارسال پاسخ لازم است وارد شده یا ثبت‌نام کنید

ورود یا ثبت‌نام