我正在试图弄清楚如何使用contentful.com中的api。我用以下视图创建了一个简单的MVC5应用程序:
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Contentful Index</h2>
<div id="pic">Pic should go here
</div>
@section Scripts{
<script type="text/javascript">
jQuery(document).ready(function () {
var client = contentful.createClient({
accessToken: 'b4c0n73n7fu1',
space: 'cfexampleapi'
});
var asset = client.asset('nyancat');
$("#pic").css({ 'background-image': asset.fields.file.url });
});
</script>
}
当页面加载时,我可以看到使用fiddler我从cdn.contentful.com获得以下响应:
HTTP/1.1 200 OK
Date: Mon, 10 Mar 2014 16:54:17 GMT
Server: nginx/1.1.19
Content-Type: application/vnd.contentful.delivery.v1+json
X-Contentful-Request-Id: 85f-830919841
ETag: "7a92346b83c581d30e36cad903578c5a"
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: Accept,Accept-Language,Authorization,Cache-Control,Content-Length,Content-Range,Content-Type,DNT,Destination,Expires,If-Match,If-Modified-Since,If-None-Match,Keep-Alive,Last-Modified,Origin,Pragma,Range,User-Agent,X-Http-Method-Override,X-Mx-ReqToken,X-Requested-With,X-Contentful-Version,X-Contentful-Content-Type,X-Contentful-Organization
Access-Control-Allow-Methods: GET,HEAD,OPTIONS
Access-Control-Max-Age: 86400
Cache-Control: max-age=0
Content-Length: 724
Accept-Ranges: bytes
Via: 1.1 varnish
Age: 3578
X-Served-By: cache-lcy1120-LCY
X-Cache: HIT
X-Cache-Hits: 1
Vary: Accept-Encoding
Keep-Alive: timeout=10, max=50
Connection: Keep-Alive
{
"fields": {
"title": "Nyan Cat",
"file": {
"fileName": "Nyan_cat_250px_frame.png",
"contentType": "image/png",
"details": {
"image": {
"width": 250,
"height": 250
},
"size": 12273
},
"url": "//images.contentful.com/cfexampleapi/4gp6taAwW4CmSgumq2ekUm/9da0cd1936871b8d72343e895a00d611/Nyan_cat_250px_frame.png"
}
},
"sys": {
"space": {
"sys": {
"type": "Link",
"linkType": "Space",
"id": "cfexampleapi"
}
},
"type": "Asset",
"id": "nyancat",
"revision": 1,
"createdAt": "2013-09-02T14:56:34.240Z",
"updatedAt": "2013-09-02T14:56:34.240Z",
"locale": "en-US"
}
}
然后我在Chrome控制台中显示以下错误:
未捕获的TypeError:无法读取未定义的属性“文件”。
我已经尝试了console.log(asset)
,它确实告诉我它未定义。谁能告诉我哪里出错了?
答案 0 :(得分:2)
根据documentation,似乎client.asset()函数是异步的。试试这个:
var asset = client.asset('nyancat').then(function(asset){
$("#pic").css({ 'background-image': asset.fields.file.url });
});