简体   繁体   English

从JS访问REST API

[英]Access to REST API from JS

Need access to REST API from JS code, using jQuery ajax: 需要使用jQuery ajax从JS代码访问REST API:

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): API文档(所有示例均为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: 我用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. 在配置ajax请求数据时遇到问题。 So any help would be greatly appreciated. 因此,任何帮助将不胜感激。

UPDATE: Changed my JS code: 更新:更改了我的JS代码:

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: 在Chrome开发人员模式下出现此错误: 在此处输入图片说明

Are you using CORS request? 您是否正在使用CORS请求?

If no then change datatype to "json" instead "dataType: "jsonp". 如果否,则将数据类型更改为“ json”,而不是“ dataType:” jsonp”。

if you are doing CORS then enable CORS request then you need to add the php code to allow CORS request. 如果您正在执行CORS,然后启用CORS请求,则需要添加php代码以允许CORS请求。

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

check this link CORS with php headers 检查此链接CORS与PHP标题

Json data format: Json数据格式:

 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 注意:方法:JOSNP不允许使用“ POST”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM