Help

Simple POST Script error 'SyntaxError: Unexpected token C in JSON at position 0,,'

Topic Labels: Extensions
3268 3
cancel
Showing results for 
Search instead for 
Did you mean: 
Ewan_Farry
5 - Automation Enthusiast
5 - Automation Enthusiast

Hi,

I have added a fairly simple scripting block that accesses an endpoint on my application. The error when running this is below, but can’t for the life of me work out what this is referring to.

Has anyone got any ideas?

ERROR

SyntaxError: Unexpected token C in JSON at position 0

at Unexpected token C in JSON at position 0

let token = await input.textAsync("Insert Token")
let table = base.getTable("test");
let record = await input.recordAsync('Pick a record',table)
let initialRaw = record.getCellValue("updatedcontent")
let recordid = "60cf7b6133fed78cdae3ca48"

let env = await input.buttonsAsync('Choose Environment', 
['Test', 
'Live'])
var exampleRequest = {
    "items":[
        {"ID":"1234",
        "name":"Mr Smith"};
        
var exampleRaw = JSON.stringify(exampleRequest)
let raw = JSON.stringify(initialRaw)
let url=''
if (env=='live')
    {
        url= 'https://live.com/user/'+recordid
    }
else
    {
        url='https://test.com/user/'+recordid
    }

console.log(url)
console.log(initialRaw)
console.log(raw)
console.log(exampleRequest)
console.log(exampleRaw)

//POST API LOCATION call
    var myHeaders = new Headers();
    myHeaders.append("Authorization", "Bearer "+token);
    myHeaders.append("Content-Type", "application/json")
    myHeaders.append("Accept", "application/json")
    
    var requestPostOptions = {
        method: 'POST',
        headers: myHeaders,
        redirect: 'follow',
        body: exampleRaw
        };
    console.log(requestPostOptions)
    let orderResponse = await fetch(url, requestPostOptions);
    let finalResponse = await orderResponse.json()
    console.log(finalResponse)
3 Replies 3

When you set exampleRequest you are missing a closing ] and a closing }

var exampleRequest = {
    "items":[
        {"ID":"1234",
        "name":"Mr Smith"}
    ]
};
        
var exampleRaw = JSON.stringify(exampleRequest)

Hi,

Thanks very much, but this error was just part of me trimming the JSON down to an example format.

The syntax error still shows, not sure what it could be?

Screenshot 2021-07-21 at 17.01.45

The error indicates JSON parsing is failing somewhere. The only place where JSON is being parsed in your example is this line:

let finalResponse = await orderResponse.json()

Can you check whether the response from your api is valid JSON? E.g. by logging this:

console.log(orderResponse.text());