简体   繁体   English

SyntaxError: Unexpected token ' in JSON at position 0

[英]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 运行 API

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.我已经绑定了替换 JSON 周围的引号,然后它说无效令牌 U。

You do in fact have a ' single-quote character in the string you pass to your post endpoint.实际上,在传递给 post 端点的字符串中确实有一个'单引号字符。

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.正如您所发现的那样,将 JSON 字符串放入像curl这样的 shell 命令中是一种臭名昭著的痛苦。 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? 将JSON直接存储在带有变量的bash脚本中?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM