首页 > 解决方案 > SyntaxError:位置 1 curl 请求的 JSON 中的意外标记 u

问题描述

任何人都知道为什么在 powershell 上运行此请求时会出现此错误?

curl.exe -d '{"username" : "username"}' -H "Content-Type: application/json" -X POST http://localhost:5200/auth

index.js 文件:

const dialogflow = require("dialogflow");
const uuid = require("uuid");
const express = require("express");
const StreamChat = require("stream-chat").StreamChat;
const cors = require("cors");
const dotenv = require("dotenv");

const port = process.env.PORT || 5200;

async function runSample(text, projectId = process.env.GOOGLE_PROJECT_ID) {
  const sessionId = uuid.v4();

  const sessionClient = new dialogflow.SessionsClient();
  const sessionPath = sessionClient.sessionPath(projectId, sessionId);

  const request = {
    session: sessionPath,
    queryInput: {
      text: {
        text: text,
        languageCode: "en-US",
      },
    },
  };

  const responses = await sessionClient.detectIntent(request);

  const result = responses[0].queryResult;
  if (result.action === "input.unknown") {
    // If unknown, return the original text
    return text;
  }

  return result.fulfillmentText;
}

dotenv.config();

const app = express();
app.use(express.json());
app.use(cors());

const client = new StreamChat(process.env.API_KEY, process.env.API_SECRET);

const channel = client.channel("messaging", "dialogflow", {
  name: "Dialogflow chat",
  created_by: { id: "admin" },
});

app.post("/dialogflow", async (req, res) => {
  const { text } = req.body;

  if (text === undefined || text.length == 0) {
    res.status(400).send({
      status: false,
      message: "Text is required",
    });
    return;
  }

  runSample(text)
    .then((text) => {
      channel.sendMessage({
        text: text,
        user: {
          id: "admin",
          image: "ignorethis",
          name: "Admin bot",
        },
      });
      res.json({
        status: true,
        text: text,
      });
    })
    .catch((err) => {
      console.log(err);
      res.json({
        status: false,
      });
    });
});

app.post("/auth", async (req, res) => {
  const username = req.body.username;
  
  const token = client.createToken(username);

  await client.updateUser({ id: username, name: username }, token);

  await channel.create();

  await channel.addMembers([username, "admin"]);

  await channel.sendMessage({
    text: "Welcome to this channel. Ask me few questions",
    user: { id: "admin" },
  });

  res.json({
    status: true,
    token,
    username,
  });
});

app.listen(port, () => console.log(`App listening on port ${port}!`));

包.json

{
 "name": "server",
 "version": "1.0.0",
 "main": "index.js",
 "license": "MIT",
 "dependencies": {
   "cors": "^2.8.5",
   "dialogflow": "^4.0.3",
   "dotenv": "^8.2.0",
   "express": "^4.17.1",
   "stream-chat": "^2.9.0",
   "uuid": "^8.3.2"
}

如果有人知道可能导致问题的原因,我将不胜感激,因为我迷路了

编辑:所以我按照建议将格式固定为:

curl.exe -d "{'username' : 'username'}" -H "Content-Type: application/json" -X POST http://localhost:5200/auth

现在我得到 SyntaxError: Unexpected token ' in JSON
   at JSON.parse in powershell 的位置 1,它转换为:

SyntaxError: Unexpected token ' in JSON at the position 1 在服务器上

再次感谢。

标签: javascriptjsoncurl

解决方案


以下格式的 curl 命令在 Linux 平台上运行良好,但在 Windows 上失败

curl ... -d '{“用户名”:“用户名”}' ...

在 Windows 中,我们必须使用以下格式:

curl.exe -d "{'username' : 'username'}" -H "Content-Type: application/json" -X POST http://localhost:5200/auth

基本上shell将双引号视为语法的一部分并将它们剥离,因此您需要将它们转义

curl.exe -d "{\"username\":\"username\"}" -H "Content-Type: application/json" -X POST http://localhost:5200/auth

有关更多信息,请参阅此答案


推荐阅读