How to use the fetch api with a .cfm file?

Viewed 410

I'm trying to fetch a checkin.cfm file from within my index.cfm using the fetch api. All I'm getting is a 500 Server Error. Is there something different I need to do with ColdFusion?

JavaScript

fetch("./src/checkin.cfm")
    .then(function (response) {
        return response.text();
    })
    .then(function (body) {
        document.querySelector("#checkin").innerHTML = body;
    });

index.cfm

<cfoutput>
  <div id="checkin"></div>

  <script src="js/app.js"></script>
</cfoutput>

checkin.cfm

<cfoutput>

    <cfset session_valid =  application.lib.check_session_valid()>

    <h1>Hello World</h1>
</cfoutput>
2 Answers

You need to Serialise your data in the ‘CFML’ template:

checkin.cfm

OPTION 1:

<cfset data = StructNew()>

<cfset data['session_valid'] =  application.lib.check_session_valid()>

<cfset data['html'] = '<h1>Hello World</h1>'>

<cfoutput>
#SerializeJSON(data)#
</cfoutput>

OPTION 2:

<cfset data = StructNew()>
    
<cfset data['session_valid'] =  application.lib.check_session_valid()>

<cfsavecontent variable="html">
<h1>I am a whole page of HTML</h1>
</cfsavecontent>
    
<cfset data['html'] = html>
    
<cfoutput>
#SerializeJSON(data)#
</cfoutput>

Also, please make sure that you have set the correct:

Access-Control-Allow-Origin

If your client side code is on a different server/port to your CFML template. In production, this probably isn't an issue, but, if like me, you use Angular, which runs locally on port 4200, and your Coldfusion Application Server runs on port 8500, then this header becomes very important.

In your JavaScript, you need to parse the JSON response:

fetch("./src/checkin.cfm")
.then(function (response) {
    return response.text();
})
.then(function (json) {
    var response = JSON.parse(json);
    console.log('response: ',response);
    if('html' in response){
        document.querySelector("#checkin").innerHTML = response['html'];
    }
});
  

I have tested this, and it works 100%, so if you are still getting an error, I would suggest you look at the response using:

Firefox Dev Tools -> Network -> XHR -> Response

And see if Coldfusion is throwing an error in checkin.cfm, due to a problem with:

application.lib.check_session_valid()

According to this SO question, you're using fetch correctly with response.text() to render the HTML from the request.

Check your browser's dev tools:

  • Network tab
  • filter to checkin.cfm, should have a 500 status
  • click that line and preview the response.

Follow P Mascar's suggestion and start with plain HTML to make sure the request and response works, then start adding CFML to dynamically generate HTML. It could be the case that the application variable you're referenced isn't defined yet in the context of the fetch request.

Related