1

I have added a fairly simple scripting block in Airtable that post an update via an endpoint on my application. The error when running this is below, but can’t work out what this is referring to.

Thinking it might be something simple, 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)
Ivan
  • 34,531
  • 8
  • 55
  • 100
Ewan Farry
  • 49
  • 4

1 Answers1

0

You're not sending valid JSON to the server.

The hint was when the JSON parser literally told you the exact character that tripped up the interpreter - throws don't get any cleaner than that. The culprit is a capital "C" in a string assigned to either the exampleRaw or raw variable.

Can't get any more specific without seeing the actual base and its tables that you're working with. But hopefully that won't be necessary and you likely even figured it out by now.

On a somewhat related note; if you're serious about getting better at JS, there are some unrelated pointers about making your code more readable that we could go over. As that would have made answering your question easier and it can still make maintaining your code way easier further down the line.

But I didn't want to spend half an hour writing an unsolicited criticism of an otherwise decent jab at this kind of problem (for a relative newcomer to the language that I assume you are and definitely wouldn't want to discourage from coding as much as possible). Between that and your question being over a month old as of today, I'll just leave it at that for now.