weixin_33691700 2017-03-29 09:00 采纳率: 0%
浏览 124

jQuery / Ajax Rest API请求

I'm trying to make an rest api request to realla https://realla.co/api/#/ from localhost, I have an api key and can make the request via PHP but having issues using ajax:

var URL = "https://realla.co/api/v1/listings/search";
var usr = 'api';
var psw = 'hidden';
$.ajax({
  type: "POST",
  dataType: "json",
  contentType: "application/json",
  url: URL,
  crossDomain: true,
  beforeSend: function(xhr) {
    xhr.setRequestHeader("Authorization", "Basic " + btoa(usr + ":" + psw))
  },
  success: function(result) {
    console.log('success');
  },
  error: function(req, status, err) {
    console.log('Something went wrong', status, err);
  }
});

Returns the error

XMLHttpRequest cannot load https://realla.co/api/v1/listings/search. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://dw.dev' is therefore not allowed access. The response had HTTP status code 403.

I tried to fix that problem with https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en but still get the same message.

I've added the following function (running Wordpress):

/*
 * Modify HTTP header
 */
function new_headers($headers) {

    if (!is_admin()) {
        $headers['Access-Control-Allow-Origin'] = '*';   
        $headers['Access-Control-Allow-Methods'] = 'GET, POST, PATCH, PUT, DELETE, OPTIONS';   
        $headers['Access-Control-Allow-Headers'] = 'Origin, Content-Type, X-Auth-Token';   

    }

    return $headers;     
}
add_filter('wp_headers', 'new_headers');

I've tried other APIs (Facebook) and that works but I wonder if I'm missing something with this.

The documentation for Realla is pretty thin, but I wonder if I'm doing something wrong.

Thanks

  • 写回答

2条回答 默认 最新

  • weixin_33696822 2017-03-29 09:10
    关注

    let's try this

    it will work

    Add header in requested resource file

     <?php
    
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
        header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');
     ?>
    
    评论

报告相同问题?

悬赏问题

  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序