簡體   English   中英

SyntaxError: Unexpected token " in JSON at position 0

[英]SyntaxError: Unexpected token " in JSON at position 0

我的表達請求有誤。 我有這個取:

fetch(`http://localhost:4200/dist/js/server.min.js`, {
    method: "POST",
    // mode: 'no-cors',
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify(`<html><body><div style="background-color: yellow;"><p>Hello World!</p></div></body></html>`),
  }).then((response) => {
      console.log(response)
  })

我的快遞服務器有這樣的代碼:

const { exec }   = require("child_process"),
      express    = require("express"),
      bodyParser = require('body-parser'),
      webshot    = require('webshot'),
      PORT       = 4200,
      app        = express(),
      cors       = require('cors')

// app.use(cors())

app.use((req, res, next) => {
    res.append('Access-Control-Allow-Origin', 'http://localhost:4242');
    res.append('Access-Control-Allow-Methods', 'POST', 'GET', 'OPTIONS');
    res.append('Access-Control-Allow-Headers', 'Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With');
    res.append('Access-Control-Allow-Credentials', 'true');
    next();
    
});

// app.use(express.json());
app.use(bodyParser.json());

app.get('/dist/js/server.min.js', (req, res) => {
    res.send('<h1>Hello</h1>')
})

app.post('/', function(req, res) {
    htmlData = req.body
    screen(htmlData) // just my function
});

app.listen(PORT, () => {
    console.log(`What's my age again? ${PORT}, I guess.`)
});

我在瀏覽器中遇到了這個錯誤:

POST http://localhost:4200/dist/js/server.min.js 400 (Bad Request)

這在控制台中:

SyntaxError: Unexpected token " in JSON at position 0
    at JSON.parse (<anonymous>)
    at createStrictSyntaxError (/home/joe/Documents/vscode-projects/html-projects/swipeskins/node_modules/body-parser/lib/types/json.js:158:10)
    at parse (/home/joe/Documents/vscode-projects/html-projects/swipeskins/node_modules/body-parser/lib/types/json.js:83:15)
    at /home/joe/Documents/vscode-projects/html-projects/swipeskins/node_modules/body-parser/lib/read.js:121:18
    at invokeCallback (/home/joe/Documents/vscode-projects/html-projects/swipeskins/node_modules/body-parser/node_modules/raw-body/index.js:224:16)
    at done (/home/joe/Documents/vscode-projects/html-projects/swipeskins/node_modules/body-parser/node_modules/raw-body/index.js:213:7)
    at IncomingMessage.onEnd (/home/joe/Documents/vscode-projects/html-projects/swipeskins/node_modules/body-parser/node_modules/raw-body/index.js:273:7)
    at IncomingMessage.emit (events.js:198:15)
    at endReadableNT (_stream_readable.js:1139:12)
    at processTicksAndRejections (internal/process/task_queues.js:81:17)

我猜,服務器在解析 json 數據時存在問題。 但為什么? 代碼有什么問題?

非常感謝您抽出寶貴的時間,如果您對我的情況有一些想法,我將非常感謝您的來信。

JSON 的頂級數據類型是字符串:

 JSON.stringify(`<html>...</html>`);

當前版本的 JSON 規范允許 JSON 文本中的頂級數據類型為任何JSON 數據類型。

原始版本僅允許 object 或數組。

錯誤消息說,將"作為第一個字符是一個錯誤,這意味着它不支持字符串作為頂級數據類型(因此實現了原始規范)。


更改 JSON 的結構,使其以 object 或數組開頭:

{
    "html": "<html>...</html>"
}

或更改您發送的數據格式:

"Content-Type: text/html"

 body: "<html>...</html>" // without JSON.stringify

顯然,您需要更改服務器端代碼以接受更改后的格式。

問題是 express JSON 正文解析器默認只接受可以解析為 JSON對象的輸入。 但是,您可以通過禁用“嚴格”解析將其更改為接受其他類型的有效 JSON 數據(包括字符串,如在 OP 中):

app.use(express.json({strict: false}));

這是為我工作的解決方法。

參考: https://github.com/expressjs/express/issues/1725#issuecomment-22844485

在請求正文中,您沒有解析 DOM 元素,因此您可以執行以下操作:

const parser = new DOMParser();
const raw = '<html><body><div style="background-color: yellow;"><p>Hello World!</p></div></body></html>';
const body = parser.parseFromString(raw, 'text/html');

fetch(`http://localhost:4200/dist/js/server.min.js`, {
    method: "POST",
    // mode: 'no-cors', // If you use 'no-cors' you will not get response body and some headers
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify(body),
  }).then((response) => {
      console.log(response);
  })

暫無
暫無

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

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