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 echarts动画效果失效的问题。官网下载的例子。
  • ¥60 许可证msc licensing软件报错显示已有相同版本软件,但是下一步显示无法读取日志目录。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加