簡體   English   中英

“語法錯誤:在 position 0 處的 JSON 中出現意外的令牌 <”

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

在處理類似 Facebook 的內容提要的 React 應用程序組件中,我遇到了一個錯誤:

Feed.js:94 undefined "parsererror" "SyntaxError: Unexpected token < in JSON at position 0

我遇到了類似的錯誤,結果證明是渲染 function 中的 HTML 中的錯字,但這里似乎不是這種情況。

更令人困惑的是,我將代碼回滾到更早的已知工作版本,但我仍然收到錯誤消息。

Feed.js:

import React from 'react';

var ThreadForm = React.createClass({
  getInitialState: function () {
    return {author: '', 
            text: '', 
            included: '',
            victim: ''
            }
  },
  handleAuthorChange: function (e) {
    this.setState({author: e.target.value})
  },
  handleTextChange: function (e) {
    this.setState({text: e.target.value})
  },
  handleIncludedChange: function (e) {
    this.setState({included: e.target.value})
  },
  handleVictimChange: function (e) {
    this.setState({victim: e.target.value})
  },
  handleSubmit: function (e) {
    e.preventDefault()
    var author = this.state.author.trim()
    var text = this.state.text.trim()
    var included = this.state.included.trim()
    var victim = this.state.victim.trim()
    if (!text || !author || !included || !victim) {
      return
    }
    this.props.onThreadSubmit({author: author, 
                                text: text, 
                                included: included,
                                victim: victim
                              })
    this.setState({author: '', 
                  text: '', 
                  included: '',
                  victim: ''
                  })
  },
  render: function () {
    return (
    <form className="threadForm" onSubmit={this.handleSubmit}>
      <input
        type="text"
        placeholder="Your name"
        value={this.state.author}
        onChange={this.handleAuthorChange} />
      <input
        type="text"
        placeholder="Say something..."
        value={this.state.text}
        onChange={this.handleTextChange} />
      <input
        type="text"
        placeholder="Name your victim"
        value={this.state.victim}
        onChange={this.handleVictimChange} />
      <input
        type="text"
        placeholder="Who can see?"
        value={this.state.included}
        onChange={this.handleIncludedChange} />
      <input type="submit" value="Post" />
    </form>
    )
  }
})

var ThreadsBox = React.createClass({
  loadThreadsFromServer: function () {
    $.ajax({
      url: this.props.url,
      dataType: 'json',
      cache: false,
      success: function (data) {
        this.setState({data: data})
      }.bind(this),
      error: function (xhr, status, err) {
        console.error(this.props.url, status, err.toString())
      }.bind(this)
    })
  },
  handleThreadSubmit: function (thread) {
    var threads = this.state.data
    var newThreads = threads.concat([thread])
    this.setState({data: newThreads})
    $.ajax({
      url: this.props.url,
      dataType: 'json',
      type: 'POST',
      data: thread,
      success: function (data) {
        this.setState({data: data})
      }.bind(this),
      error: function (xhr, status, err) {
        this.setState({data: threads})
        console.error(this.props.url, status, err.toString())
      }.bind(this)
    })
  },
  getInitialState: function () {
    return {data: []}
  },
  componentDidMount: function () {
    this.loadThreadsFromServer()
    setInterval(this.loadThreadsFromServer, this.props.pollInterval)
  },
  render: function () {
    return (
    <div className="threadsBox">
      <h1>Feed</h1>
      <div>
        <ThreadForm onThreadSubmit={this.handleThreadSubmit} />
      </div>
    </div>
    )
  }
})

module.exports = ThreadsBox

在 Chrome 開發者工具中,錯誤似乎來自這個 function:

 loadThreadsFromServer: function loadThreadsFromServer() {
    $.ajax({
      url: this.props.url,
      dataType: 'json',
      cache: false,
      success: function (data) {
        this.setState({ data: data });
      }.bind(this),
      error: function (xhr, status, err) {
        console.error(this.props.url, status, err.toString());
      }.bind(this)
    });
  },

帶有下划線的console.error(this.props.url, status, err.toString()行。

由於看起來該錯誤似乎與從服務器中提取 JSON 數據有關,因此我嘗試從空白數據庫開始,但錯誤仍然存在。 該錯誤似乎是在無限循環中調用的,大概是因為 React 不斷嘗試連接到服務器並最終導致瀏覽器崩潰。

編輯:

我已經使用 Chrome 開發工具和 Chrome REST 客戶端檢查了服務器響應,數據似乎是正確的 JSON。

編輯2:

It appears that though the intended API endpoint is indeed returning the correct JSON data and format, React is polling http://localhost:3000/?_=1463499798727 instead of the expected http://localhost:3001/api/threads .

我在端口 3000 上運行 webpack 熱重載服務器,並在端口 3001 上運行快速應用程序以返回后端數據。 令人沮喪的是,我上次處理它時它工作正常,但找不到我可能改變的東西來破壞它。

錯誤消息的措辭與您在運行JSON.parse('<...')時從 Google Chrome 獲得的內容相對應。 我知道您說服務器正在設置Content-Type:application/json ,但我被引導相信響應正文實際上是 HTML。

Feed.js:94 undefined "parsererror" "SyntaxError: Unexpected token < in JSON at position 0"

帶有下划線的console.error(this.props.url, status, err.toString())行。

err實際上是在jQuery中拋出的,並作為變量err傳遞給您。 該行加下划線的原因僅僅是因為那是您記錄它的地方。

我建議您添加到日志記錄中。 查看實際的xhr (XMLHttpRequest) 屬性以了解有關響應的更多信息。 嘗試添加console.warn(xhr.responseText) ,您很可能會看到正在接收的 HTML。

您正在從服務器接收 HTML(或 XML),但dataType: json告訴 jQuery 解析為 JSON。 檢查 Chrome 開發工具中的“網絡”選項卡以查看服務器響應的內容。

這最終對我來說是一個權限問題。 我試圖訪問我沒有使用 cancan 授權的 url,所以 url 被切換到users/sign_in 重定向的 url 響應 html,而不是 json。 html 響應中的第一個字符是<

SyntaxError: 位置 0 處的 JSON 中的意外標記 <


您得到的是 HTML 文件(或 XML)而不是 json。

Html 文件以<!DOCTYPE html>開頭。

我通過在我的fetch方法中忘記https://來“實現”這個錯誤:

fetch(`/api.github.com/users/${login}`)
    .then(response => response.json())
    .then(setData);

我驗證了我的預感:

我將響應記錄為文本而不是 JSON。

fetch(`/api.github.com/users/${login}`)
    .then(response => response.text())
    .then(text => console.log(text))
    .then(setData);

是的,一個html文件。

解決方案:

我通過在我的fetch方法中添加回https://來修復錯誤。

fetch(`https://api.github.com/users/${login}`)
    .then(response => response.json())
    .then(setData)
    .catch(error => (console.log(error)));

就我而言,我正在運行這個 webpack,結果發現本地 node_modules 目錄中的某個地方出現了一些損壞。

rm -rf node_modules
npm install

...足以讓它再次正常工作。

我遇到了這個錯誤“SyntaxError: Unexpected token m in JSON at position”,其中標記“m”可以是任何其他字符。

原來我在使用 RESTconsole 進行 DB 測試時遺漏了 JSON 對象中的雙引號之一,為 {"name: "math"},正確的應該是 {"name": "math"}

我費了好大勁才弄清楚這個笨拙的錯誤。 恐怕其他人也會遇到類似的問題。

當您將響應定義為application/json並且您獲得 HTML 作為響應時,會發生此錯誤。 基本上,當您使用 JSON 響應為特定 url 編寫服務器端腳本但錯誤格式為 HTML 時,就會發生這種情況。

我面臨着同樣的問題。

我從$.ajax方法中刪除了dataType:'json'

那些正在使用create-react-app並嘗試獲取本地 json 文件的人。

create-react-app一樣, webpack-dev-server用於處理請求,並為每個請求提供index.html服務。 所以你得到

SyntaxError: 位置 0 處的 JSON 中的意外標記 <。

要解決這個問題,您需要彈出應用程序並修改webpack-dev-server配置文件。

您可以按照此處的步驟操作。

簡而言之,如果您收到此錯誤或類似錯誤,那僅意味着一件事。 也就是說,在我們的代碼庫中的某個地方,我們期望處理有效的 JSON 格式,但我們沒有得到。 例如:

var string = "some string";
JSON.parse(string)

會拋出一個錯誤,說

Uncaught SyntaxError: 位置 0 處 JSON 中的意外標記

因為, string中的第一個字符是s & 現在不是有效的 JSON。 這也可能在兩者之間引發錯誤。 喜歡:

var invalidJSON= '{"foo" : "bar", "missedquotehere : "value" }';
JSON.parse(invalidJSON)

會拋出錯誤:

VM598:1 Uncaught SyntaxError: Unexpected token v in JSON at position 36

因為我們故意遺漏了 JSON 字符串invalidJSON中第 36 位的引號。

如果你解決這個問題:

var validJSON= '{"foo" : "bar", "missedquotehere" : "value" }';
JSON.parse(validJSON)

會給你一個 JSON 格式的對象。

現在,這個錯誤可以在任何地方和任何框架/庫中拋出。 大多數時候,您可能正在閱讀不是有效 JSON 的網絡響應。 所以調試這個問題的步驟可以是:

  1. curl或點擊您正在調用的實際 API。
  2. 記錄/復制響應並嘗試使用JSON.parse解析它。 如果您遇到錯誤,請修復它。
  3. 如果沒有,請確保您的代碼沒有改變/更改原始響應。

我的情況是錯誤是我沒有將返回值分配給變量的結果。 以下導致錯誤消息:

return new JavaScriptSerializer().Serialize("hello");

我將其更改為:

string H = "hello";
return new JavaScriptSerializer().Serialize(H);

沒有變量 JSON 無法正確格式化數據。

就我而言,對於 Azure 托管的 Angular 2/4 站點,由於 mySite 路由問題,我對 mySite/api/... 的 API 調用正在重定向。 因此,它從重定向頁面返回 HTML,而不是 api JSON。 我在 web.config 文件中為 api 路徑添加了一個排除項。

在本地開發時我沒有收到此錯誤,因為站點和 API 位於不同的端口上。 可能有更好的方法來做到這一點......但它奏效了。

<?xml version="1.0" encoding="UTF-8"?>
 
<configuration>
    <system.webServer>
        <rewrite>
        <rules>
        <clear />
 
        <!-- ignore static files -->
        <rule name="AngularJS Conditions" stopProcessing="true">
        <match url="(app/.*|css/.*|fonts/.*|assets/.*|images/.*|js/.*|api/.*)" />
        <conditions logicalGrouping="MatchAll" trackAllCaptures="false" />
        <action type="None" />
        </rule>
 
        <!--remaining all other url's point to index.html file -->
        <rule name="AngularJS Wildcard" enabled="true">
        <match url="(.*)" />
        <conditions logicalGrouping="MatchAll" trackAllCaptures="false" />
        <action type="Rewrite" url="index.html" />
        </rule>
 
        </rules>
        </rewrite>
    </system.webServer>
</configuration>

2022 更新:幾年前寫過這篇文章。 我將此建議稱為一種解決方法 - 直接修復。 更好的托管模式是不要嘗試將這些api路徑托管在您的網站路徑下; 相反,將它們完全托管在單獨的基本 URL 上。 對於我的用例示例,API 和 Web 路徑將是完全獨立的 Azure Web 服務,並且會獲得不同的 URL 端點。

對於未來的谷歌人:

如果服務器端函數崩潰,將生成此消息。

或者,如果服務器端函數甚至不存在(即函數名稱中的錯字)

所以 - 假設您正在使用 GET 請求......並且一切看起來都很完美,並且您已經對所有內容進行了三重檢查......

再次檢查該 GET 字符串。 我的是:

'/theRouteIWant&someVar=Some value to send'

應該

'/theRouteIWant?someVar=Some value to send'
               ^

碰撞 ! (......隱形服務器......)

Node/Express 發回了非常有用的信息:
Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0

我的問題是我以不正確 JSON 格式的string取回數據,然后我試圖解析它。 simple example: JSON.parse('{hello there}')將在 h 處給出錯誤。 在我的情況下,回調 url 在對象之前返回了一個不必要的字符: employee_names([{"name":....並且在 0 處出現錯誤。我的回調 URL 本身有一個問題,修復后只返回對象.

一般而言,當解析包含語法錯誤的 JSON 對象時會發生此錯誤。 想想這樣的事情,其中​​ message 屬性包含未轉義的雙引號:

{
    "data": [{
        "code": "1",
        "message": "This message has "unescaped" quotes, which is a JSON syntax error."
    }]
}

如果您的應用程序中有 JSON,那么最好通過JSONLint運行它以驗證它沒有語法錯誤。 通常情況並非如此,但根據我的經驗,通常是從 API 返回的 JSON 是罪魁禍首。

當向 HTTP API 發出 XHR 請求時,該 API 返回帶有Content-Type:application/json; charset=UTF-8 Content-Type:application/json; charset=UTF-8標頭在響應正文中包含無效的 JSON,您將看到此錯誤。

如果服務器端 API 控制器不正確地處理語法錯誤,並且它作為響應的一部分被打印出來,這將破壞返回的 JSON 的結構。 一個很好的例子是在響應正文中包含 PHP 警告或通知的 API 響應:

<b>Notice</b>:  Undefined variable: something in <b>/path/to/some-api-controller.php</b> on line <b>99</b><br />
{
    "success": false,
    "data": [{ ... }]
}

95% 的情況下,這對我來說是問題的根源,盡管在其他回復中有所提及,但我覺得它沒有被清楚地描述。 希望這會有所幫助,如果您正在尋找一種方便的方法來追蹤哪個 API 響應包含 JSON 語法錯誤,我已經為此編寫了一個Angular 模塊

這是模塊:

/**
 * Track Incomplete XHR Requests
 * 
 * Extend httpInterceptor to track XHR completions and keep a queue 
 * of our HTTP requests in order to find if any are incomplete or 
 * never finish, usually this is the source  of the issue if it's 
 * XHR related
 */
angular.module( "xhrErrorTracking", [
        'ng',
        'ngResource'
    ] )
    .factory( 'xhrErrorTracking', [ '$q', function( $q ) {
        var currentResponse = false;

        return {
            response: function( response ) {
                currentResponse = response;
                return response || $q.when( response );
            },
            responseError: function( rejection ) {
                var requestDesc = currentResponse.config.method + ' ' + currentResponse.config.url;
                if ( currentResponse.config.params ) requestDesc += ' ' + JSON.stringify( currentResponse.config.params );

                console.warn( 'JSON Errors Found in XHR Response: ' + requestDesc, currentResponse );

                return $q.reject( rejection );
            }
        };
    } ] )
    .config( [ '$httpProvider', function( $httpProvider ) {
        $httpProvider.interceptors.push( 'xhrErrorTracking' );
    } ] );

更多細節可以在上面引用的博客文章中找到,我沒有在這里發布所有在這里找到的東西,因為它可能並不完全相關。

確保響應為 JSON 格式,否則會觸發此錯誤。

在使用 fetch API 和 POST 方法調用 React 中的 API 時,我遇到了同樣的錯誤。

前:

fetch('/api/v1/tour',{
      method:"POST",
      headers:{"Content-type":"json/application"},
      body:JSON.stringify(info)
    })
    .then((response)=>response.json())
    .then((json)=>{
      if(json.status === 'success')
        alert(json.message)
      else
        console.log('something went wrong :(')
    }).catch(e=>console.log(e))

我通過將標題更改為{"Content-type":"application/json"}解決了該錯誤:

后:

fetch('/api/v1/tour',{
      method:"POST",
      headers:{"Content-type":"application/json"},
      body:JSON.stringify(info)
    })
    .then((response)=>response.json())
    .then((json)=>{
      if(json.status === 'success')
        alert(json.message)
      else
        console.log('something went wrong :(')
    }).catch(e=>console.log(e))

在教程之后,我收到了相同的錯誤消息。 我們的問題似乎是 ajax 調用中的 'url: this.props.url' 。 在 React.DOM 中,當您創建元素時,我的看起來像這樣。

ReactDOM.render(
    <CommentBox data="/api/comments" pollInterval={2000}/>,
    document.getElementById('content')
);

好吧,這個 CommentBox 的 props 中沒有 url,只有數據。 當我切換url: this.props.url -> url: this.props.data時,它對服務器進行了正確的調用,我得到了預期的數據。

我希望它有所幫助。

這可能是舊的。 但它只是發生在 Angular 中,我的代碼中請求和響應的內容類型不同。 所以檢查標題

 let headers = new Headers({
        'Content-Type': 'application/json',
        **Accept**: 'application/json'
    });

在反應軸

axios({
  method:'get',
  url:'http://  ',
 headers: {
         'Content-Type': 'application/json',
        Accept: 'application/json'
    },
  responseType:'json'
})

jQuery 阿賈克斯:

 $.ajax({
      url: this.props.url,
      dataType: 'json',
**headers: { 
          'Content-Type': 'application/json',
        Accept: 'application/json'
    },**
      cache: false,
      success: function (data) {
        this.setState({ data: data });
      }.bind(this),
      error: function (xhr, status, err) {
        console.error(this.props.url, status, err.toString());
      }.bind(this)
    });
  },
 

這個錯誤的可能性是壓倒性的。

就我而言,我發現問題是在package.json中添加homepage導致了問題。

值得檢查:在package.json更改:

homepage: "www.example.com"

hompage: ""   

如其他答案所述,格式錯誤的 JSON 或 HTML 而不是 JSON 是此問題的根本原因,但是在我的情況下,我無法可靠地復制此錯誤,就好像服務器有時返回有效的 JSON,而有時返回一些東西其他類似 HTML 錯誤頁面或類似內容。

為了避免它完全破壞頁面,我求助於手動嘗試解析返回的內容,並分享它以防它幫助其他人為他們解決它。

const url = "https://my.server.com/getData";

fetch(url).then(response => {
  if (!response.ok) return; // call failed

  response.text().then(shouldBeJson => { // get the text-only of the response
    let json = null;
    try {
      json = JSON.parse(shouldBeJson); // try to parse that text
    } catch (e) {
      console.warn(e); // json parsing failed
      return;
    };
    if (!json) return; // extra check just to make sure we have something now.

    // do something with my json object
  });
});

雖然這顯然不能解決問題的根本原因,但它仍然可以幫助更優雅地處理問題並在失敗時采取某種合理的措施。

對於 CRA 制作的 React 應用程序,我們在獲取任何<dummy.json>文件的 JSON 數據時可能會遇到兩個主要問題。

我的項目中有我的 dummy.json 文件,並試圖從該文件中獲取 JSON 數據,但出現兩個錯誤:

"SyntaxError: Unexpected token < in JSON at position 0 .

在 Chrome 或任何瀏覽器的“網絡”選項卡中的響應中,我得到了一個 HTML 文件而不是實際的 JSON 數據。

以下是解決我的問題的兩個主要原因。

  1. 您的 JSON 數據在 JSON 文件中無效。
  2. 可能是 JSON 文件沒有為此正確加載,因此您只需重新啟動 React 服務器。 這是我的問題,React 中。

反應直接運行或訪問公用文件夾而不是 src 文件夾。

我是如何解決的:

我將我的文件移動到公用文件夾中,並且可以直接在 src 文件夾的任何文件中訪問。

我的公共文件夾

在 Redux action.js 中進行 REST 調用:

export const fetchDummy = ()=>{
return (dispatch)=>{
        dispatch(fetchDummyRequest());
        fetch('./assets/DummyData.json')
        .then(response => {
            if (!response.ok) {
                throw new Error("HTTP error " + response.status);
            }
            return response.json();
        })
        .then(result => {
            dispatch(fetchDummySuccess(result))
        })
        .catch(function (err) {
          dispatch(fetchDummyFailure(err))
        })
    }
}

在花了很多時間之后,我發現在我的情況下,問題是在我的 package.json 文件中定義了“主頁”,這使我的應用程序無法在 firebase 上運行(同樣的“令牌”錯誤)。 我使用 create-react-app 創建了我的 react 應用程序,然后我使用 READ.me 文件上的 firebase 指南部署到 github 頁面,意識到我必須做額外的工作才能讓路由器工作,然后切換到 firebase。 github 指南在 package.json 上添加了主頁鍵並導致部署問題。

Protip:在本地 Node.js 服務器上測試 json? 確保您還沒有路由到該路徑的東西

'/:url(app|assets|stuff|etc)';

對我來說,當我作為 JSON 返回的對象的屬性之一引發異常時,就會發生這種情況。

public Dictionary<string, int> Clients { get; set; }
public int CRCount
{
    get
    {
        var count = 0;
        //throws when Clients is null
        foreach (var c in Clients) {
            count += c.Value;
        }
        return count;
    }
}

添加一個空檢查,為我修復它:

public Dictionary<string, int> Clients { get; set; }
public int CRCount
{
    get
    {
        var count = 0;
        if (Clients != null) {
            foreach (var c in Clients) {
                count += c.Value;
            }
        }
        return count;
    }
}

只是一些基本的檢查,確保你沒有在 json 文件中注釋掉任何東西

//comments here will not be parsed and throw error

在 python 中,您可以在將結果發送到 html 模板之前使用 json.Dump(str)。 使用此命令字符串轉換為正確的 json 格式並發送到 html 模板。 將此結果發送到 JSON.parse(result) 后,這是正確的響應,您可以使用它。

對於某些人來說,這可能會對你們有所幫助:我在 Wordpress REST API 方面也有過類似的經歷。 我什至使用 Postman 來檢查我是否有正確的路線或端點。 后來我發現我不小心在我的腳本中放了一個“回聲” - 鈎子:

調試並檢查您的控制台

錯誤原因

所以基本上,這意味着我打印了一個不是 JSON 的值,它與導致 AJAX 錯誤的腳本混合 - “SyntaxError: Unexpected token r in JSON at position 0”

我有同樣的問題。 我正在使用一個簡單的node.js服務器將響應發送到Angular 7中制作的客戶端。最初,我正在發送response.end('Hello world from nodejs server'); 客戶端,但不知何故Angular無法解析它。

就我而言(后端),我使用的是 res.send(token);

當我更改為 res.send(data); 時,一切都得到了解決;

如果一切正常並按預期發布,您可能需要檢查這一點,但錯誤不斷在您的前端彈出。

在我的情況下,標題中的“Bearer”存在問題,理想情況下它應該是“Bearer”(結束字符后的空格),但在我的情況下,它是“Bearer”,字符后沒有空格。 希望它可以幫助某人!

就我而言,事實證明我從中獲取數據的端點 URL 已更改 - 而我並不知道這一點。 當我更正 URL 時,我開始獲得正確的 JSON。

如果您在 Chrome 擴展程序中收到此錯誤,則可能很難追蹤,尤其是在您安裝擴展程序時發生。 但是,我找到了一種更容易的方法。

我有一個 Chrome 擴展程序,它在安裝插件時從我的網絡服務器調用一些腳本,拉下一些默認設置。 我收到錯誤:

SyntaxError: Unexpected token < in JSON at position 0 in _generated_background_page.html

當您進入擴展程序時,找到您的擴展程序,單擊“背景頁面”超鏈接,檢查器將為它打開。 然后,轉到網絡並按CTRL + R 現在,您將看到背景頁面必須加載的所有內容。

單擊每個,尤其是連接回遠程服務器的。 您將在網絡選項卡中看到標題,然后是預覽。 查看每個項目的預覽。 如果您看到此數據的預期標題以外的內容,或者您​​看到錯誤,那么這可能是您的原因。

就我而言,我的服務器腳本正在調用另一個腳本,並且該腳本中存在錯誤,因為在運行時缺少變量,這使得我的application/json標頭與它發送的數據不匹配,從而導致意外的令牌錯誤。

就我而言,在測試 API 節點中發送數據時,JSON 對象末尾有一個額外的逗號,例如:

 POST http://localhost:9000/api/posts/ Content-Type: application/json { "title": "sokka", "description": "hope this works", "username": "sokka blog4", }

所以我只需要刪除多余的逗號並發送這種數據:

 POST http://localhost:9000/api/posts/ Content-Type: application/json { "title": "sokka", "description": "hope this works", "username": "sokka blog4" }

我正在使用 RESTclient 擴展來測試我的 API。

在大多數情況下,當 API 引發文本格式錯誤時,我會收到此錯誤。 我的建議是查看錯誤文本內容以找出問題所在。

  1. jQuery => 設置數據類型:'文本'

  2. fetch => reponse.text() 而不是 reponse.json()

檢查您發出請求的端點地址。 如果拼寫錯誤,這可能是錯誤的原因,因為端點返回 HTML

只是為了增加答案,當您的 API 響應包括

<?php{username: 'Some'}

當您的后端使用 PHP 時,可能會出現這種情況。

這可能是由於您的 javascript 代碼正在查看一些 json 響應而您收到了其他類似文本的內容。

如果其他人正在使用 Mozilla 中 Web API 上的“Using Fetch”文檔中的 fetch:(這非常有用: https ://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch)

  fetch(api_url + '/database', {
    method: 'POST', // or 'PUT'
    headers: {
     'Content-Type': 'application/json'
    },
    body: qrdata //notice that it is not qr but qrdata
  })
  .then((response) => response.json())
  .then((data) => {
    console.log('Success:', data);
  })  
  .catch((error) => {
  console.error('Error:', error);  });

這是在函數內部:

async function postQRData(qr) {

  let qrdata = qr; //this was added to fix it!
  //then fetch was here
}

我正在將我認為是對象的東西傳遞給我的函數qr ,因為qr看起來像這樣: {"name": "Jade", "lname": "Bet", "pet":"cat"}但我一直在獲取語法錯誤。 當我把它分配給別的東西時: let qrdata = qr; 有效。

如果您嘗試在控制台中運行這行代碼:

JSON.parse(undefined);

你會得到同樣的錯誤信息:

"SyntaxError: Unexpected token < in JSON at position 0"

因此,您的應用正在嘗試解析無效的 JSON undefined

也許會出現一些權限錯誤,只是嘗試切換瀏覽器並從授權帳戶登錄。

JSON中位置0的意外令牌<

解決此錯誤的一個簡單方法是在styles.less文件中編寫注釋。

暫無
暫無

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

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