moo1210
moo1210

Reputation: 73

SyntaxError: Unexpected token ' in JSON at position 0

const express = require("express");
const bodyParser = require("body-parser");
const app = express();
const fs = require("fs");
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());



// http://expressjs.com/en/starter/static-files.html
app.use(express.static("public"));

const dbFile = "./.data/sqlite.db";
const exists = fs.existsSync(dbFile);
const sqlite3 = require("sqlite3").verbose();
const db = new sqlite3.Database(dbFile);

db.serialize(() => {
  if (!exists) {
    db.run(
      "CREATE TABLE UserData (UserID INTEGER, Points INTEGER, Warnings INTEGER, Suspendions INTEGER, Blacklisted TEXT)"
    );
    console.log("New table UserData created!");

  }
});

app.post("/adduserdatacard", (request, response) => {
  console.log(`add to userdata ${request.body.userid}`);


  const userid = request.body.userid;
  const points = request.body.points;
  db.run(`INSERT INTO UserData (UserID,Points,Warnings,Suspendions,Blacklisted) VALUES (?,?,0,0,'false')`,userid, points, error => {
    if (error) {
      response.send({ message: "error" });
    } else {
      response.send({ message: "success" });
    }
  });
});

I'm confused due to the fact that no ' is in my code. I am running the API via CURL with

curl -H "Content-Type: application/json" -X POST -d '{"UserID":1,"Points":1234}' http://lts-database.glitch.me

Why would it be telling me such an error if there is no quote? I've already tied replacing the quote around the JSON and it says invalid token U then.

Upvotes: 1

Views: 2125

Answers (1)

O. Jones
O. Jones

Reputation: 108641

You do in fact have a ' single-quote character in the string you pass to your post endpoint.

This is the string you pass

'{"UserID":1,"Points":1234}'

It should be

"{\"UserID\":1,\"Points\":1234}"

Putting JSON strings in shell commands like curl is a notorious pain in the neck, as you are discovering. You must wrap them in double quotes and then escape the double quotes inside them.

You may find this question helpful. Store JSON directly in bash script with variables?

Upvotes: 2

Related Questions