bug^君 2019-01-14 20:28 采纳率: 25%
浏览 43

避免在Rest API中使用CORS

I'm having a problem to make a call to a rest API.

In the document (FAQ) of the web application there is an example that use AJAX request to make the call. Here an example:

var url = 'https://example.com/yyy';

$.ajax({
    type: 'POST',
    url: url,
    cache: false,
    data: {
        opt: JSON.stringify(example)
    },
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    success: function (result)
    {
        console.log(result);
    } });

I created a local page with this code to made the post to the API that is located on a remote server but I receive an error about CORS.

Is there any solution to circumvent this problem? I tried to use firefox plugin to allow CORS but it didn't solve the problem. The session is authenticated via form before use the endpoint.

  • 写回答

1条回答 默认 最新

  • 斗士狗 2019-01-20 15:24
    关注

    I see several issues:

    1. Try to run the code from a domain and not from local disk (alternatively you can consider using https://crossorigin.me/ )
    2. How does the authentication work? if with cookies you need to add withCredentials to the ajax request.
    3. Make sure the API returns Access-Control-Allow-Origin: foo header where foo is the domain your code runs in. If you also used withCredentials, you should add Access-Control-Allow-Credentials: true
    评论

报告相同问题?

悬赏问题

  • ¥15 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀