drkjzk3359 2016-09-30 15:48
浏览 289

从JS访问REST API

Need access to REST API from JS code, using jQuery ajax:

function tryQwintry () {
    var data = {
        "params[weight]" : "100",
        "params[dimensions]" : "100x100x100",
        "params[delivery_pickup]" : "msk_1",
        "params[insurance]" : "false",
        "params[items_value]" : "350",
        "params[retail_pricing]" : "1"
    };

    $.ajax({
        url: "http://logistics.qwintry.com/api/cost",
        type: "POST",
        dataType: "jsonp",
        contentType: "application/json",
        headers: {"Authorization":"Bearer " + MY_API_KEY},
        data: data,
        success: function (cost) {
            console.log("стоимость доставки $"+cost);
        },
        error: getErrorMsg
    });
}

Documentation of API (all examples are PHP):

<?php
    define('SITE_URL', 'logistics.qwintry.com');
    define('API_KEY', 'YOUR_API_KEY'); //don't forget to set your key!

    $url =  'http://'. SITE_URL .'/api/cost';


    $data = array ( 
        'params' => array(
            'weight' => 5, // in lb
            'delivery_pickup' => 'msk_1', // full list of pickup points can be retrieved from /api/locations-list
            'insurance' => true,
            'items_value' => 500, // declaration items total cost in USD
            'retail_pricing' => true // retail / wholesale pricing?
        ),
     );
    $data_string = http_build_query($data);

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer '. API_KEY));
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS,  $data_string);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    $response = curl_exec($ch);
    curl_close($ch);
    var_dump($response);

Same thing I've coded in Java:

public double getCostPickup(String weight, String dimensions, String toPickup, String insurance, String value) throws Exception {

    Map<String, Object> params = new HashMap<>();
    params.put("params[weight_kg]", weight);
    params.put("params[dimensions_cm]", dimensions);
    params.put("params[delivery_pickup]", toPickup);
    params.put("params[insurance]", insurance);
    params.put("params[items_value]", value);
    params.put("params[retail_pricing]", RETAIL_PRICING);

    String url = BASE_URL+"/api/cost";
    HttpResponse<JsonNode> jsonResponse = Unirest.post(url).fields(params).asJson();
    return getCost(jsonResponse, insurance);
}

Have problems with configuring data of ajax request. So any help would be greatly appreciated.

UPDATE: Changed my JS code:

function tryQwintry () {
    var data = {
        "params[weight]" : "100",
        "params[dimensions]" : "100x100x100",
        "params[delivery_pickup]" : "msk_1",
        "params[insurance]" : "false",
        "params[items_value]" : "350",
        "params[retail_pricing]" : "1"
    };

    $.ajax({
        url: "http://logistics.qwintry.com/api/cost",
        type: "POST",
        dataType: "json",
        contentType: "application/json",
        headers: {"Authorization" : "Bearer"+MY_API_KEY, "Access-Control-Allow-Origin" : "true"},
        data: JSON.stringify(data),
        success: function (cost) {
            console.log("стоимость доставки $"+cost);
        },
        error: getErrorMsg
    });
}

Getting this error in Chrome's developers mode: enter image description here

  • 写回答

1条回答 默认 最新

  • douzhang7184 2016-09-30 16:02
    关注

    Are you using CORS request?

    If no then change datatype to "json" instead "dataType: "jsonp".

    if you are doing CORS then enable CORS request then you need to add the php code to allow CORS request.

    header("Access-Control-Allow-Origin: *");
    

    check this link CORS with php headers

    Json data format:

     var data = {
            weight : 100,
            dimensions : "100x100x100",
            delivery_pickup : "msk_1",
            insurance : false,
            items_value : 350,
            retail_pricing : 1
        };
    
    $.ajax({
        url: "http://logistics.qwintry.com/api/cost",
        dataType: "jsonp",
        contentType: "application/json",
        headers: {"Authorization":"Bearer " + MY_API_KEY},
        data: JSON.stringify(data),
        success: function (cost) {
            console.log("стоимость доставки $"+cost);
        },
        error: getErrorMsg
    });
    

    Note: method: "POST" is not allowed with JOSNP

    评论

报告相同问题?

悬赏问题

  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图