programing

Respect Js: Uncapted (in promise) SyntaxError:위치 0의 JSON에 예기치 않은 토큰이 있습니다.

css3 2023. 3. 26. 11:42

Respect Js: Uncapted (in promise) SyntaxError:위치 0의 JSON에 예기치 않은 토큰이 있습니다.

이에 Json 파일을 사용하고 .이것에 대해서, 사용하고 있다.fetch

Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0

뭐가 잘못됐는지 모르겠어요.JSON도 검증했습니다.

handleGetJson(){
  console.log("inside handleGetJson");
  fetch(`./fr.json`)
    .then((response) => response.json())
    .then((messages) => {console.log("messages");});
}

마이제이슨(fr.json)

{
  "greeting1": "(fr)choose an emoticon",
  "addPhoto1": "(fr)add photo",
  "close1": "(fr)close"
}

의 헤더를 합니다.Content-Type ★★★★★★★★★★★★★★★★★」Acceptapplication/json.

handleGetJson(){
  console.log("inside handleGetJson");
  fetch(`./fr.json`, {
      headers : { 
        'Content-Type': 'application/json',
        'Accept': 'application/json'
       }

    })
    .then((response) => response.json())
    .then((messages) => {console.log("messages");});
}

이 솔루션은 다음과 같습니다.- data.json 파일을 src에서 퍼블릭디렉토리로 이동했습니다.그런 다음 fetch API를 사용하여 파일을 가져옵니다.

fetch('./data.json').then(response => {
          console.log(response);
          return response.json();
        }).then(data => {
          // Work with JSON data here
          console.log(data);
        }).catch(err => {
          // Do something for an error here
          console.log("Error Reading data " + err);
        });

문제는 리액트 앱을 컴파일한 후 가져오기 요청이 실제로 리액트 앱의 공개 디렉토리인 URL "http://localhost:3000/data.json"에서 파일을 찾는다는 것입니다.그러나 유감스럽게도 컴파일 중에 react app data.json 파일은 src에서 퍼블릭디렉토리로 이동되지 않습니다.따라서 data.json 파일을 src에서 퍼블릭디렉토리로 명시적으로 이동해야 합니다.

이 에러는 수신할 수 있습니다만, 실제의 문제에 대한 경고일 가능성이 있습니다.저의 경우, JSON에 에러 상태로서 문제가 있는 것은 아니고, JSON 데이터를 1차적으로 풀링 할 수 없는 404가 발생하고 있기 때문에, 이 에러가 발생하고 있었습니다.

를 수정한 은 '''를 하기 .fetch .json로컬프로젝트에 ..json파일에 액세스할 수 있어야 합니다. , , , , , , , , , , , , , , , 등의 에 넣을 수 .public폴더는 프로젝트 루트에 있습니다.json 404는 200으로 .Unexpected token < in JSON at position 0에러가 해결되었습니다.

같은 에러가 발생하고 있었습니다.이것은 API가 문자열을 반환하고 있었기 때문입니다만, fetch call에서는 json을 기대하고 있었습니다.

response => response.json()

을 반환하면 을 반환하지 API를 만약 당신의 API가 json을 반환하지 않아야 한다면 그냥 하지 마세요.response.json()

"/src" 폴더에서 데이터를 가져오려고 할 때도 같은 문제가 발생했습니다.파일을 "/public"으로 이동하면 문제가 해결되었습니다.

fetch에서도 같은 문제가 발생하여 axios로 전환하기로 했습니다.문제를 바로 해결했습니다. 코드 조각입니다.

var axios = require('axios');

  var config = {
    method: 'get',
    url: 'http://localhost:4000/'
  };
  
  axios(config)
  .then(function (response) {
    console.log(JSON.stringify(response.data));
  })
  .catch(function (error) {
    console.log(error);
  });

로컬이 아닌 다른 웹 서버에 데이터를 요청했는데도 같은 문제가 있었습니다.응답 상태 코드는 200이었지만, 디폴트로 JSON 포맷으로 보내졌는데도 데이터를 받지 못했습니다.(단순한) 문제는 URL에 'https://'를 넣는 것을 잊어버렸기 때문에 처음에 로컬호스트를 사용했습니다.

요청하신 Promise 응답에 대해

response.json() 

그러나 서버가 json 응답을 보내는 경우, 특히 서버 측에서 노드 Js를 사용하는 경우 잘 작동합니다.

다시 한 번 체크하고 서버가 노드일 경우 지정된 응답대로 json을 전송하는지 확인합니다.JS 응답은 다음과 같습니다.

res.json(YOUR-DATA-RESPONSE)

여기서 제안되고 있는 몇 가지 메서드가 나에게도 효과가 있음을 확인합니다.fetch()가 찾고 있는 퍼블릭디렉토리에 로컬 .json 파일을 저장해야 합니다(http://localhost:3000/을 참조).예를 들어, 이 fetch()src/App.js 파일에서 사용합니다.

componentDidMount(){
  fetch('./data/json-data.json')
  .then ( resp1 => resp1.json() )
  .then ( users1 => this.setState( {cards : users1} ) )
}

public/data/json-data.json을 만들었습니다.

그때는 모든 게 괜찮았어요. :)

API " " " " " " " " " " " ( ,Proxy error: Could not proxy request ... , 「」<html><body>NOT FOUND</body></html>를 참조해 주세요.

이 경우 1) 유효한 json 응답 오류 또는 2) 텍스트 페이로드(응답 페이로드가 유효한 json이 아닌 경우)를 폴백으로 처리해야 합니다.

두 가지 사례를 모두 처리하기 위해 다음과 같이 제안합니다.

  // parse response as json, or else as txt
  static consumeResponseBodyAs(response, jsonConsumer, txtConsumer) {
    (async () => {
      var responseString = await response.text();
      try{
        if (responseString && typeof responseString === "string"){
         var responseParsed = JSON.parse(responseString);
         if (Api.debug) {
            console.log("RESPONSE(Json)", responseParsed);
         }
         return jsonConsumer(responseParsed);
        }
      } catch(error) {
        // text is not a valid json so we will consume as text
      }
      if (Api.debug) {
        console.log("RESPONSE(Txt)", responseString);
      }
      return txtConsumer(responseString);
    })();
  }

그러면 나머지 핸들러를 보다 쉽게 조정할 수 있습니다.

class Api {
  static debug = true;

  static contribute(entryToAdd) {
    return new Promise((resolve, reject) => {
      fetch('/api/contributions',
        { method: 'POST',
          headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' },
          body: JSON.stringify(entryToAdd) })
      .catch(reject);
      .then(response => Api.consumeResponseBodyAs(response,
          (json) => {
            if (!response.ok) {
              // valid json: reject will use error.details or error.message or http status
              reject((json && json.details) || (json && json.message) || response.status);
            } else {
              resolve(json);
            }
          },
          (txt) => reject(txt)// not json: reject with text payload
        )
      );
    });
  }

응답을 문자열로 변환한 후 JSON으로 해석해 보십시오.이것으로 오류를 해결할 수 있습니다.아래는 같은 코드입니다.

let resp = JSON.stringify(response);
res = JSON.parse(resp);

API(사용하고 있는 것)가 대응하는 JSON을 송신하고 있지 않은 경우에 발생할 수 있습니다.404 페이지 또는 HTML/XML 응답과 같은 응답이 나타날 수 있습니다.

src 폴더에 .json 파일이 있었습니다.공용 폴더로 이동하기만 하면 작동

저는 같은 문제로 고민했지만, 몇 가지 조사를 한 후에 해결책을 찾았습니다.이 문제는 입력 오류로 인해 발생할 수 있습니다.콘솔에서 오류 유형을 알 수 있습니다.

을 사용하다py에서는 더블 를 했습니다.파이다CORS__ORIGIN_ALLOW_ALL = TrueCORS_ORIGIN_ALLOW_ALL = True.

문제가 지속되어 이 'API Fetch 메서드'를 변경했는데 정상적으로 동작했습니다.

refreshList() {
  fetch(process.env.REACT_APP_API+ "department")
    .then((response) => response.json())
    .then((data) => {
      this.setState({ deps: data });
    });
}

대상:

refreshList() {
  fetch("http://127.0.0.1:8000/" + "department")
    .then((response) => response.json())
    .then((data) => {
      this.setState({ deps: data });
    });
}

새 , 파일을 추가하여 env 파일을 .process.env.REACT_APP_URL ★★★★★★★★★★★★★★★★★」process.env.REACT_APP_API_KEY[ ]이렇게 하다을 다시 되었습니다.env 파일을 다시 추가하면 문제가 해결되었습니다.

"method: 'GET' 추가

let query = {
      method: 'GET',
      headers: {
        authToken: token,
        "Content-Type": "application/json",
    },
 };

public/datas/datas.json에 데이터가 있는 경우:

export default class App extends React.Component {
    constructor(props) {
        super(props);
    }
    async componentDidMount() {
        const response = await fetch("datas/datas.json");
        const datas = await response.json();
        console.log(datas);
    }
...

처음에 아래 코드 행을 맨 위에 추가합니다.

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

fr.json공개 폴더 내에 있습니다.그 후 다음과 같이 코드를 작성합니다.

fetch(`http://localhost:${port}/fr.json`)
    .then((response) => response.json())
    .then((messages) => {console.log("messages");});

나는 오류를 받고 있었다.패키지에 "대리"를 추가했을 뿐입니다.json과 에러는 사라졌습니다.이 오류는 단순히 리액트 앱이 실행되고 있는 포트와 동일한 포트에서 API 요청이 이루어졌기 때문입니다.백엔드 서버가 실행되고 있는 포트에 API 콜이 이루어지도록 프록시를 제공해야 합니다.

이 문제는 대부분 React/Client 앱에서 발생합니다.클라이언트에 이 행 추가package.json해결하다

"실행":"filename://localhost:filename/"

주의: 5000을 서버가 동작하고 있는 포토 번호로 치환해 주세요.

레퍼런스:Create-React-app을 Node.js 백엔드 API와 함께 사용하는 방법

언급URL : https://stackoverflow.com/questions/37269808/react-js-uncaught-in-promise-syntaxerror-unexpected-token-in-json-at-posit