你能帮帮我吗?我试图在我的ColdFusion应用程序消费响应。我只是想在使用真正的API之前先用这个假的API试试。
我创建了一个组件,里面有两个函数。我的cfc看起来像这样:
photoUploadNew.cfc
<cfcomponent displayname="test" hint="testing.." output="yes">
<cfsetting enablecfoutputonly="true" showdebugoutput="true">
<cffunction name="start" access="public" output="no" returntype="any" description="initialize the component">
<cfset variables.testUrl = "https://jsonplaceholder.typicode.com/posts">
<cfreturn this>
</cffunction>
<cffunction access="public" output="false" name="testGetReq" displayname="TestGetReq" description="testing" returntype="any">
<cfset variables.testUrl = "https://jsonplaceholder.typicode.com/posts">
<cfhttp
result="httpResponsetest"
url="#variables.testUrl#"
timeout="30"
method="get"
>
<cfhttpparam
type="header"
name="Content-Type"
value="application/json"
/>
</cfhttp>
</cfhttp>
<cfreturn httpResponsetest>
</cffunction>
</cfcomponent>
在我的cfm页面。我正在尝试实例化这个组件并打印我得到的任何响应,但我无法在那里打印任何东西。
<cfset testObj = CreateObject("component","usedGear_admin.cfc.photoUploadNew").testGetReq()>
<cfoutput >
#testObj#
</cfoutput>
任何帮助都将是非常感激的。
我认为你在这里使用的cfhttp
结果是错误的。当我们执行cfhttp
调用时,
<cfhttp
method="get"
result="httpResponsetest"
url="https://jsonplaceholder.typicode.com/posts"
timeout="30"
>
</cfhttp>
他们尝试以下操作,您将看到httpResponsetest
有多个密钥。API提供的数据会出现在httpResponsetest.fileContent
中。大多数时候还有Mimetype,Responseheader,Statuscode
等
<cfdump var="#httpResponsetest.fileContent#">
这里你可以看到数据是JSON格式的。这意味着您需要对它们进行反序列化才能使用它。
<cfdump var="#deserializeJSON(httpResponsetest.fileContent)#">
可以反序列化它并从函数返回。除此之外,您还需要处理API响应错误的情况。