Alp Durak
Alp Durak

Reputation: 25

SyntaxError: Unexpected token \n in JSON at position

I have a roblem while directing a request from Cloud Flare workers to my API. When I catch the error I get this:

SyntaxError: Unexpected token \n in JSON at position 240

when I did some research I saw some articles about it being about JSON.parse. But I couldn't find the solution.

Example Request Body:

{"link": "link", "provider": "company", "oauth": "key", "testText": "text"}

Cloud Flare Workers Code:

addEventListener('fetch', function (event) {
const { request } = event;
const response = handleRequest(request).catch(handleError)
event.respondWith(response)
})

async function handleRequest(request) {
const realBody = JSON.parse(`${await request.json()}`
            .replace(/\n/g, "\\n")
            .replace(/\r/g, "\\r")
            .replace(/\t/g, "\\t")
            .replace(/\f/g, "\\f"));
const stringifiedJSON = JSON.stringify(realBody);
const init = {
  body: stringifiedJSON,
  method: "POST",
  headers: {
    "content-type": "application/json;charset=UTF-8",
  },
};
const initLog = {
  body: JSON.stringify({ msg: { discountBodyStringified: realBody }}),
  method: "POST",
  headers: {
    "content-type": "application/json;charset=UTF-8",
  },
}

const responseLogger = await fetch("https://example.com/log", initLog)
console.log(responseLogger)
console.log(init)
const response = await fetch("https://example.com", init)
return new Response("tweet sent!")
}

  function handleError(error) {
  console.error('Uncaught error:', error)

  const { stack } = error
  const initLog = {
  body: JSON.stringify({ msg: { error: stack || error }}),
  method: "POST",
  headers: {
    "content-type": "application/json;charset=UTF-8",
  },
}

const responseLogger = fetch("https://example.com/log", initLog)
return new Response(stack || error, {
status: 500,
headers: {
  'Content-Type': 'text/plain;charset=UTF-8'
}
})
}

Upvotes: 0

Views: 1190

Answers (1)

Ismoil Hasanov
Ismoil Hasanov

Reputation: 31

problem is not in the code, the problem in request which you are or front app is sending somewhere you lived extra comma or didnt close field. For example:

{ "name": "Alice", }

this will give same error as SyntaxError: Unexpected token \n in JSON at position because extra comma is there or

{ "name": "Alice }

this also will throw error because I didnt close quotes

Upvotes: 1

Related Questions