簡體   English   中英

將Graphql查詢作為JSON字符串傳遞時接收到意外的令牌錯誤

[英]Receiving Unexpected Token Error When Passing Graphql query as JSON string

先謝謝您的幫助。 我正在使用java中的testng測試GRAPHQL API。

我試圖將偽裝成JSON的agraphQL對象作為帖子發送,但是當嘗試將字符串打包為JSON對象時,我收到以下錯誤:

SyntaxError: Unexpected token B<br> &nbsp; &nbsp;at Object.parse (native)<br> &nbsp; &nbsp;at parse (/app/node_modules/body-parser/lib/types/json.js:88:17)<br> &nbsp; &nbsp;at /app/node_modules/body-parser/lib/read.js:116:18<br> &nbsp; &nbsp;at invokeCallback (/app/node_modules/raw-body/index.js:262:16)<br> &nbsp; &nbsp;at done (/app/node_modules/raw-body/index.js:251:7)<br> &nbsp; &nbsp;at IncomingMessage.onEnd (/app/node_modules/raw-body/index.js:307:7)<br> &nbsp; &nbsp;at emitNone (events.js:80:13)<br> &nbsp; &nbsp;at IncomingMessage.emit (events.js:179:7)<br> &nbsp; &nbsp;at endReadableNT (_stream_readable.js:913:12)<br> &nbsp; &nbsp;at _combinedTickCallback (internal/process/next_tick.js:74:11)<br> &nbsp; &nbsp;at process._tickDomainCallback (internal/process/next_tick.js:122:9)

我試圖創建的JSON對象在這里:

"{\"query\":\"{marketBySlug(slug: \"Boston\") {countryCode}}\"}"

我已經發現我的問題是將波士頓標識為字符串的轉義引號打破了內部構造的Graphql查詢字符串,但我不知道如何解決這個問題。

嘗試這個:

"{\"query\":\"{marketBySlug(slug: \\\"Boston\\\") {countryCode}}\"}"

您應該使用參數化查詢,而不是弄亂字符串和轉義。 您的代碼將如下所示:

String query =
        "query MarketBySlug($slug: String!) {\n" +
        "  marketBySlug(slug: $slug) {\n" +
        "    countryCode\n" +
        "  }\n" +
        "}";

    Map<String, Object> variables = new HashMap<>();
    variables.put("slug", slug);

    given()
    .body(new QueryDto(query, variables))
    .when()
    .post("/graphql")
    .then()
    .contentType(JSON)
    .statusCode(HttpStatus.OK.value())
    .body("data.marketBySlug.countryCode", equalTo(countryCode));

QueryDto只是一個簡單的dto,包含兩個字段(查詢和變量),setter和getter。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM