2017-06-14 58 views
0

我有一个简单的烧瓶宁静的API,我喜欢做一个Ajax请求来检索一些数据。但是,ajax请求包含数据作为一个查询字符串,这使得该API无效的API。下面是代码:阿贾克斯休息请求的网址没有查询字符串

将烧瓶的RESTful API:

from flask import Flask, request 
from flask_restful import Resource, Api 

app = Flask(__name__) 
api = Api(app) 

articles = {"1001":"article1001"} 

class Stock(Resource): 
    def get(self, article_number): 
     return {article_number: articles[article_number]} 

api.add_resource(Stock, '/stock/<string:article_number>') 

的AJAX调用是:

var arg = '1001' 
function testApiGet(arg){ 
    $.ajax({ 
    type: "GET", 
    data: {article_number: arg}, 
    url:'http://127.0.0.1:5000/stock', 
    success: function(data){ 
     console.log("API works fine") 
    } 
    }) 
} 

寻找在本地主机服务器的日志,所述AJAX尝试请求以下网址:

"GET /stock?article_number=1001 HTTP/1.1" 404 - 

虽然我想要实现的是从阿贾克斯到这个网址的请求:

"GET /stock/1001" 

我试着改变ajax请求到这个,它的工作原理,但我觉得这不是正确的技术。

function testApiGet(arg){ 
    $.ajax({ 
    type: "GET", 
    // I add arg to the url as a normal string. 
    url:'http://127.0.0.1:5000/stock/'+arg, 
    success: function(data){ 
     console.log("API works fine") 
    } 
    }) 
} 
+1

是的,没有其他方式发送没有参数传递的数据,您必须尝试'url:'http://127.0.0.1:5000/stock /'+ arg'或将请求类型更改为' POST'并将参数作为发布数据传递,所以你的请求URL看起来像''GET/stock /'' omething。 –

+0

最后一个很不错,没有其他内置的解决方案 –

回答

0

我认为这是做这件事的清洁方式,但既然你手头拥有jQuery的,你可以简化:

var arg = '1001' 
function testApiGet(arg){  
    $.get('http://127.0.0.1:5000/stock/'+ arg, function(data) { 
    console.log("API works fine") 
    }); 
} 

和良好的措施,使用.done.fail.always:

var arg = '1001' 
function testApiGet(arg){  
    $.get('http://127.0.0.1:5000/stock/'+ arg) 
    .done(function() { 
    console.log("API works fine"); 
    }) 
    .fail(function() { 
    console.log("API DOESN'T work fine"); 
    }) 
    .always(function() { 
    console.log("Do this no matter what works or not."); 
    }); 
}