我想使用SparkAR的网络模块从URL提取数据 并显示它。
我尝试了Spark AR文档中的示例,但它并没有做很多事情:https://developers.facebook.com/docs/ar-studio/reference/classes/networkingmodule/
不要忘了添加“ jsonplaceholder.typicode.com” 首先将Spark AR列入白名单的域。 :)
// Load in the required modules
const Diagnostics = require('Diagnostics');
const Networking = require('Networking');
//==============================================================================
// Create the request
//==============================================================================
// Store the URL we're sending the request to
const url = 'https://jsonplaceholder.typicode.com/posts';
// Create a request object
const request = {
// The HTTP Method of the request
// (https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods)
method: 'POST',
// The HTTP Headers of the request
// (https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers)
headers: {'Content-type': 'application/json; charset=UTF-8'},
// The data to send, in string format
body: JSON.stringify({title: 'Networking Module'})
};
//==============================================================================
// Send the request and log the results
//==============================================================================
// Send the request to the url
Networking.fetch(url, request).then(function(result) {
// Check the status of the result
// (https://developer.mozilla.org/en-US/docs/Web/HTTP/Status)
if ((result.status >= 200) && (result.status < 300)) {
// If the request was successful, chain the JSON forward
return result.json();
}
// If the request was not successful, throw an error
throw new Error('HTTP status code - ' + result.status);
}).then(function(json) {
// Log the JSON obtained by the successful request
Diagnostics.log('Successfully sent - ' + json.title);
}).catch(function(error) {
// Log any errors that may have happened with the request
Diagnostics.log('Error - ' + error.message);
});
我所得到的是:“ >>成功发送-网络模块”
有人知道如何将json内容显示在控制台中吗?我想将其存储起来,然后在文本对象中使用它。
答案 0 :(得分:1)
在我的情况下,有一个网址可以给我一个json格式的随机项目。
URL:https://gabby-airbus.glitch.me/random
结果:{“ item”:“ Item 14”}
在代码中,替换以下行:
Diagnostics.log('Successfully sent - ' + json.title);
与此:
// show json data in console
Diagnostics.log(json.item);
// Asign json data to text object
itemText.text = json.item;
第一行显示控制台中的json数据。 第二行将json数据分配给场景中的文本对象,在本例中为“ itemText”文本对象。
完整代码:
const Diagnostics = require('Diagnostics');
const Scene = require('Scene');
const Networking = require('Networking');
const URL = 'https://gabby-airbus.glitch.me/random';
var itemText = Scene.root.find('itemText');
Networking.fetch(URL).then(function(result){
if( (result.status >=200) && (result.status < 300)){ return result.json(); }
else { throw new Error('HTTP Status Code: ' + result.status); }
}).then(function(json){
// show json data in console
Diagnostics.log(json.item);
// Asign json data to text object
itemText.text = json.item;
}).catch(function(error){
itemText = 'Failed to start';
Diagnostics.log(result.status + error);
});