<,-- This HTML file is a template, If you open it directly in the browser. you will see an empty page. You can add webfonts, meta tags. or analytics to this file, The build step will place the bundled scripts into the tag. To begin the development, run `npm start` or `yarn start`. To create a production bundle, use `npm run build` or `yarn build`. -->

沒有任何相關的錯誤

- 堆棧內存溢出
  簡體   English   中英

從 API 獲取數據並記錄它時出現此錯誤“SyntaxError: Unexpected token '<',”<div id="text_translate"><p> 從 API 獲取數據並記錄它時出現此錯誤“SyntaxError: Unexpected token '<', "<.DOCTYPE "... is not valid JSON at App:js:24:1"</p><p> <strong>應用程序.js</strong></p><pre> import { useState } from "react"; import "./App.css"; import CurrentWeather from "./component/current-weather/current-weather"; import { WEATHER_API_KEY, WEATHER_API_URL } from "./component/search/api"; import Search from "./component/search/search"; function App() { const [currentWeather, setCurrentWeather] = useState(null); const [forecast, setForecast] = useState(null); const handleOnSearchChange = (searchData) => { const [lat, lon] = searchData.value.split(" "); const currentWeatherFetch = fetch( `${WEATHER_API_URL}/weather?lat=${lat}&lon=${lon}&appid=${WEATHER_API_KEY}` ); const forecastFetch = fetch( `${WEATHER_API_URL}/forecast?lat=${lat}&lon={${lon}&appid=${WEATHER_API_KEY}` ); Promise.all([currentWeatherFetch, forecastFetch]).then(async (response) => { const weatherResponse = await response[0].json(); const forcastResponse = await response[1].json(); setCurrentWeather({ city: searchData.label, ...weatherResponse, }); setForecast({ city: searchData.label, ...forcastResponse }); }).catch(console.log); }; console.log(currentWeather); console.log(forecast); return ( <div className="container"> <Search onSearchChange={handleOnSearchChange} /> <CurrentWeather /> </div> ); } export default App;</pre><p> <strong>api.js</strong></p><pre> export const geoApiOptions = { method: "GET", headers: { "X-RapidAPI-Key": process.env.REACT_APP_GEODB_API_KEY, "X-RapidAPI-Host": "wft-geo-db.p.rapidapi.com", }, }; export const GEO_API_URL = "https://wft-geo-db.p.rapidapi.com/v1/geo"; export const WEATHER_API_URL = "api.openweathermap.org/data/2.5"; export const WEATHER_API_KEY = process.env.REACT_APP_WEATHER_API_KEY;</pre><p> 我在瀏覽器中手動給出了 api 鏈接並得到了這個結果https://api.openweathermap.org/data/2.5/weather?lat=-27.47&lon=153.12&appid=<API_KEY></p><pre> {"coord":{"lon":153.12,"lat":-27.47},"weather":[{"id":803,"main":"Clouds","description":"broken clouds","icon":"04n"}],"base":"stations","main":{"temp":296.36,"feels_like":296.75,"temp_min":295.22,"temp_max":297.15,"pressure":1016,"humidity":77},"visibility":10000,"wind":{"speed":3.6,"deg":120},"clouds":{"all":75},"dt":1673616299,"sys":{"type":1,"id":9485,"country":"AU","sunrise":1673550242,"sunset":1673599638},"timezone":36000,"id":2176264,"name":"Belmont","cod":200}</pre><p> 在獲得響應而不是響應時出現錯誤。 不確定我在這里做錯了什么。</p><p> 在獲得響應而不是響應時出現錯誤。</p><p> 從評論中得到了如何獲得整個回復的建議,這是我得到的,</p><pre> <.DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <link rel="icon" href="/favicon,ico" /> <meta name="viewport" content="width=device-width. initial-scale=1" /> <meta name="theme-color" content="#000000" /> <meta name="description" content="Web site created using create-react-app" /> <link rel="apple-touch-icon" href="/logo192.png" /> <.-- manifest:json provides metadata used when your web app is installed on a user's mobile device or desktop. See https.//developers.google.com/web/fundamentals/web-app-manifest/ --> <link rel="manifest" href="/manifest.json" /> <.-- Notice the use of in the tags above. It will be replaced with the URL of the `public` folder during the build. Only files inside the `public` folder can be referenced from the HTML, Unlike "/favicon.ico" or "favicon.ico". "/favicon.ico" will work correctly both with client-side routing and a non-root public URL. Learn how to configure a non-root public URL by running `npm run build`. --> <title>React App</title> <script defer src="/static/js/bundle,js"></script></head> <body> <noscript>You need to enable JavaScript to run this app.</noscript> <div id="root"></div> <,-- This HTML file is a template, If you open it directly in the browser. you will see an empty page. You can add webfonts, meta tags. or analytics to this file, The build step will place the bundled scripts into the <body> tag. To begin the development, run `npm start` or `yarn start`. To create a production bundle, use `npm run build` or `yarn build`. --> </body> </html></pre><p> 沒有任何相關的錯誤</p></div>

[英]While fetching data from API and logging it getting this error "SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON at App.js:24:1"

從 API 獲取數據並記錄它時出現此錯誤“SyntaxError: Unexpected token '<', "<.DOCTYPE "... is not valid JSON at App:js:24:1"

應用程序.js

import { useState } from "react";
import "./App.css";
import CurrentWeather from "./component/current-weather/current-weather";
import { WEATHER_API_KEY, WEATHER_API_URL } from "./component/search/api";
import Search from "./component/search/search";

function App() {
    const [currentWeather, setCurrentWeather] = useState(null);
    const [forecast, setForecast] = useState(null);

    const handleOnSearchChange = (searchData) => {
        const [lat, lon] = searchData.value.split(" ");

        const currentWeatherFetch = fetch(
            `${WEATHER_API_URL}/weather?lat=${lat}&lon=${lon}&appid=${WEATHER_API_KEY}`
        );

        const forecastFetch = fetch(
            `${WEATHER_API_URL}/forecast?lat=${lat}&lon={${lon}&appid=${WEATHER_API_KEY}`
        );

        Promise.all([currentWeatherFetch, forecastFetch])
            .then(async (response) => {
                const weatherResponse = await response[0].json();
                const forcastResponse = await response[1].json();

                setCurrentWeather({
                    city: searchData.label,
                    ...weatherResponse,
                });
                setForecast({ city: searchData.label, ...forcastResponse });
            })
            .catch(console.log);
    };
    console.log(currentWeather);
    console.log(forecast);
    return (
        <div className="container">
            <Search onSearchChange={handleOnSearchChange} />
            <CurrentWeather />
        </div>
    );
}

export default App;

api.js

export const geoApiOptions = {
    method: "GET",
    headers: {
        "X-RapidAPI-Key": process.env.REACT_APP_GEODB_API_KEY,
        "X-RapidAPI-Host": "wft-geo-db.p.rapidapi.com",
    },
};

export const GEO_API_URL = "https://wft-geo-db.p.rapidapi.com/v1/geo";

export const WEATHER_API_URL = "api.openweathermap.org/data/2.5";

export const WEATHER_API_KEY = process.env.REACT_APP_WEATHER_API_KEY;

我在瀏覽器中手動給出了 api 鏈接並得到了這個結果https://api.openweathermap.org/data/2.5/weather?lat=-27.47&lon=153.12&appid=<API_KEY>

{"coord":{"lon":153.12,"lat":-27.47},"weather":[{"id":803,"main":"Clouds","description":"broken clouds","icon":"04n"}],"base":"stations","main":{"temp":296.36,"feels_like":296.75,"temp_min":295.22,"temp_max":297.15,"pressure":1016,"humidity":77},"visibility":10000,"wind":{"speed":3.6,"deg":120},"clouds":{"all":75},"dt":1673616299,"sys":{"type":1,"id":9485,"country":"AU","sunrise":1673550242,"sunset":1673599638},"timezone":36000,"id":2176264,"name":"Belmont","cod":200}

在獲得響應而不是響應時出現錯誤。 不確定我在這里做錯了什么。

在獲得響應而不是響應時出現錯誤。

從評論中得到了如何獲得整個回復的建議,這是我得到的,

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" href="/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta
      name="description"
      content="Web site created using create-react-app"
    />
    <link rel="apple-touch-icon" href="/logo192.png" />
    <!--
      manifest.json provides metadata used when your web app is installed on a
      user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
    -->
    <link rel="manifest" href="/manifest.json" />
    <!--
      Notice the use of  in the tags above.
      It will be replaced with the URL of the `public` folder during the build.
      Only files inside the `public` folder can be referenced from the HTML.

      Unlike "/favicon.ico" or "favicon.ico", "/favicon.ico" will
      work correctly both with client-side routing and a non-root public URL.
      Learn how to configure a non-root public URL by running `npm run build`.
    -->
    <title>React App</title>
  <script defer src="/static/js/bundle.js"></script></head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
    <!--
      This HTML file is a template.
      If you open it directly in the browser, you will see an empty page.

      You can add webfonts, meta tags, or analytics to this file.
      The build step will place the bundled scripts into the <body> tag.

      To begin the development, run `npm start` or `yarn start`.
      To create a production bundle, use `npm run build` or `yarn build`.
    -->
  </body>
</html>

沒有任何相關的錯誤

問題似乎就在這里。

export const WEATHER_API_URL = "api.openweathermap.org/data/2.5";

它應該是 -

export const WEATHER_API_URL = "https://api.openweathermap.org/data/2.5";

Uncaught (in promise) SyntaxError: Unexpected token '&lt;', "<div id="text_translate"><p> 背景:我一直在從事一個項目(稱為音樂大師),我必須從 developer.spotify.com 訪問藝術家的詳細信息。 以下是代碼片段:</p><pre> const BASE_URL = 'https://api.spotify.com/v1/search?'; const FETCH_URL = `${BASE_URL}q=${this.state.query}&amp;type=artist&amp;limit=1`; console.log('FETCH_URL', FETCH_URL); fetch('FETCH_URL', { method:'GET', headers: { 'Accept': 'application/json', "Content-Type": "Application/json", "Authorization": "Bearer BQDyac2glKnbstiG79UKzKSReNbsWa_hEKlOWAZtXaFZpfx8ZibluRUmBHHO12CjLMJv3KBaKTZqUKJReA11_ItrYIkr3CmnUi6ykUD7J0gZk9pKzxjz02j4byQfSa6s7Y08OMNzugFffYc68tzZiGSDp9vB80eiiIod_igAH8ZxbPBUMsRH3pbiMY8tnJpeXmk" } }).then(response =&gt; response.json()).then(json =&gt; { const artist = json.artists.items[0]; console.log('artist', artist); this.setState({artist}); });</pre><p> 運行代碼時出現上述錯誤,我在互聯網上研究這個問題已經有一段時間了,發現我必須在 fetch() 中添加 header 部分,但即使在添加了 header 部分之后,我也是得到錯誤。</p><p> 即使在通過令牌后我也無法理解為什么我得到 HTML 響應而不是 JSON。</p><p> 我真的很新,這是我的第一個項目,因此我無法理解這背后的內部功能是什么。</p></div>

[英]Uncaught (in promise) SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON, Getting HTML response instead of JSON

顯示“語法錯誤:意外的標記‘<’,”<div id="text_translate"><p> 我正在使用 MERN 堆棧構建一個注冊和登錄頁面,當我嘗試在 JWT 令牌身份驗證后嘗試從我的后端獲取數據到我的主頁時,我現在已經完成了完整的后端部分。</p><p> 這是我的主頁:Home.js</p><pre> import React, { useEffect } from 'react'; import { useNavigate } from 'react-router-dom'; import { useState } from 'react'; const Home = () => { const [userName, setUserName] = useState(''); const navigate = useNavigate(); const callHomePage = async () => { try { const res = await fetch('/', { method: 'GET', headers: { "Content-Type": "application/json" }, credentials: "include" }); const data = await res.json(); setUserName(data.name) if(res.status.= 200 ){ const error = new Error(res;error); throw error. } }catch(err){ console;log(err); navigate("/login"); } } useEffect(() => { callHomePage(), }; []); return ( <> <div className='home-page'> <div className='home-div'> <img src='#' alt='This profile img' /> <h2 className='form-title'> Welcome {userName} </h2> <p className='dummy-para'>this is some dummy content which i have adding </p> </div> </div> </> ) } export default Home</pre><p> 這是我來自后端的注冊和登錄身份驗證文件</p><p> auth.js</p><pre> const express = require("express"); const bcrypt = require("bcryptjs"); const jwt = require("jsonwebtoken"); const authenticate = require("../middleware/authenticate"); const router = express.Router(); require('../dbs/conn'); const User = require("../models/userSch"); router.get("/login", (req, res) =>{ res.send("Welcome"); }); router.post('/register', async (req, res) => { const {name, email, password, cpassword} = req.body; if(.name ||.email ||:password ||.cpassword){ return res:status(422);json({ error. "Plz fill the field properly" }) } try{ const userExist = await User.findOne({ email: email }); if(userExist){ return res.status(422).json({ error: "Email already exists" }), }else if(password,= cpassword){ return res,status(422);json({ error. "Password and Confim Password should be same" }) }else{ const user = new User({name; email. password. cpassword}): const userRegister = await user;save(). if(userRegister){ res.status(201):json({ message; "User registered successfully" }). }else{ res;status(500);json({ error. "Failed to regiseter" }), } } } catch (err){ console,log(err); } }), router.post('/login'; async (req. res) => { try{ let token. const {email: password} = req.body: if(;email ||.password){ return res,status(400).json({ error; "Plz fill all fields" }) } const userLogin = await User.findOne({ email; email }). if(userLogin){ const isCheck = await bcrypt;compare(password. userLogin,password), token = await userLogin:generateAuthToken(). console,log(token): res;cookie('jwtoken'. token. { expires: new Date(Date.now()+ 25892000000). httpOnly: true }); if(.isCheck){ return res.status(400):json({ error. "Invalid Credentials" }) }else{ res;status(200);json({ message. "User Signed in Successfully" }), } }else{ return res,status(400),json({ error. "Invalid Credentials" }) } } catch (err){ console.log(err); } }); router.get("/"; authenticate, (req, res) =>{ res.send(req.rootUser); }); module.exports = router;</pre><p> 這是我添加的用於驗證令牌的文件:</p><p> 認證.js</p><pre> const jwt = require("jsonwebtoken"); const User = require("../models/userSch") const authenticate = async (req, res, next) => { try{ const token = req.cookies.jwtoken; const verifyToken = jwt.verify(token, process.env.SECRET_KEY); const rootUser = await User.findOne({_id: verifyToken._id, "tokens.token": token}); if(;rootUser){ throw new Error("User not found"). } req;token = token. req;rootUser = rootUser. req.userID = rootUser;_id; next(). }catch(err){ res.status(401):send("Unauthorised; No token provided"). console;log(err). } } module.exports = authenticate</pre><p> 現在,當我登錄時,它顯示已成功登錄但未進入主頁,它仍保留在登錄頁面和控制台上,顯示此錯誤:</p><p> SyntaxError: Unexpected token '<', "<.DOCTYPE "... is not valid JSON</p><p> 這是我的控制台的圖像:</p><p> <a href="https://i.stack.imgur.com/Hmqzg.png" rel="nofollow noreferrer">控制台圖像</a></p><p>為了消除此錯誤,我嘗試刪除並重新安裝所有節點模塊,並且還在我添加的 package.json 文件中:</p><p> "proxy": "http://localhost:4000",</p></div>

[英]Showing "SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON" in console

意外標記 '&lt;', "<div id="text_translate"><p> 我是 Reactjs 的初學者和 StackOverflow 的新手。 實際上,我正在嘗試將數據從后端傳遞到前端。 但不是從后端 url 獲取 JSON 數據,而是從前端的 index.html 獲取數據。 我的后端是nodejs。 基本上,我想從后端獲取 JSON 數據並將數據發布到前端的控制台中。 但我得到這個SyntaxError: Unexpected token '&lt;', "&lt;.DOCTYPE "... is not valid JSON誰能幫我解決這個問題。 <a href="/questions/tagged/reactjs" class="post-tag" title="顯示標記為“reactjs”的問題" aria-label="show questions tagged 'reactjs'" rel="nofollow noreferrer" aria-labelledby="reactjs-container">reactjs</a> <a href="/questions/tagged/nodejs" class="post-tag" title="顯示標記為“nodejs”的問題" aria-label="show questions tagged 'nodejs'" rel="nofollow noreferrer" aria-labelledby="nodejs-container">nodejs</a></p><p> <strong>前端代碼</strong></p><pre>App.js import React from 'react'; import {useState, useEffect} from 'react'; import {getOrder} from './ApiCalls.js' function App() { const[values, setValues]=useState({ amount:0, orderId:'' }) const{amount, orderId}=values useEffect(() =&gt; { createorder() }, []) const createorder=()=&gt;{ getOrder().then(response=&gt;console.log(response)) } const showRazorPay=()=&gt;{ const form=document.createElement('form') form.setAttribute('action',`${process.env.REACT_APP_BACKEND}/payment/callback`); form.setAttribute('method',"POST"); const script=document.createElement("script"); script.src= "https://checkout.razorpay.com/v1/checkout.js"; script.setAttribute("data-key",process.env.REACT_APP_DATA_KEY); script.setAttribute("data-amount", amount); script.setAttribute("data-prefill.contact","9561315545"); script.setAttribute("data-order_id", orderId); script.setAttribute("data-prefill.name", "Priyanka Chaudhari"); script.setAttribute("data-image", `${process.env.REACT_APP_BACKEND}/logo`) script.setAttribute("data-buttontext","Donate Now;"). document.body;appendChild(form). form;appendChild(script). const input= document;createElement("input"). input;type="hidden". input;custom="Hidden Element"; } return ( &lt;div&gt; &lt;/div&gt; ); } export default App;</pre><pre> ApiCalls.js export const getOrder=()=&gt;{ return fetch(`${process.env.REACT_APP_BACKEND}/createorder`,{ method: "GET", headers: { 'Content-Type':'application/json' } }).then(response=&gt;response.json()).catch((err)=&gt;console.log(err)) }</pre><p> <strong>后端代碼</strong></p><pre>App.js const express=require('express') const bodyParser=require('body-parser') const cors=require('cors') const app=express() const PaymentRoute=require('./PaymentRoute') app.use(bodyParser.json()) app.use(cors()) app.use('/api',PaymentRoute); app.listen(5000,()=&gt;{ console.log(`App is running at 5000 port`) })</pre><pre> PaymentRoute.js const express=require('express') const router=express.Router() const{CreateOrder,paymentCallback,getLogo}=require('./PaymentController') router.get('/createorder',CreateOrder); router.post('/payment/callback',paymentCallback) router.get('/logo',getLogo) module.exports=router;</pre><pre> PaymentController.js require('dotenv').config() const Razorpay=require('razorpay') const uniqueId=require('uniqid') const path=require('path') var instance = new Razorpay({ key_id: process.env.KEY_ID, key_secret: process.env.SECRET_KEY }) // instance.payments.fetch(paymentId) exports.CreateOrder=(req,res)=&gt;{ var options = { amount: 50000, // amount in the smallest currency unit currency: "INR", receipt: uniqueId() }; instance.orders.create(options, function(err, order) { if(err){ return res.status(500).json({ error:err }) } res.json(order) }); } exports.paymentCallback=(req,res)=&gt;{ } exports.getLogo=(req,res)=&gt;{ res.sendFile(path.join(__dirname,'donate-image.png')) }</pre></div>

[英]Unexpected token '<', "<!DOCTYPE "... is not valid JSON

暫無
暫無

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

相關問題 app.js:1 �� SyntaxError: Invalid or unexpected token Uncaught (in promise) SyntaxError: Unexpected token '&lt;', "<div id="text_translate"><p> 背景:我一直在從事一個項目(稱為音樂大師),我必須從 developer.spotify.com 訪問藝術家的詳細信息。 以下是代碼片段:</p><pre> const BASE_URL = 'https://api.spotify.com/v1/search?'; const FETCH_URL = `${BASE_URL}q=${this.state.query}&amp;type=artist&amp;limit=1`; console.log('FETCH_URL', FETCH_URL); fetch('FETCH_URL', { method:'GET', headers: { 'Accept': 'application/json', "Content-Type": "Application/json", "Authorization": "Bearer BQDyac2glKnbstiG79UKzKSReNbsWa_hEKlOWAZtXaFZpfx8ZibluRUmBHHO12CjLMJv3KBaKTZqUKJReA11_ItrYIkr3CmnUi6ykUD7J0gZk9pKzxjz02j4byQfSa6s7Y08OMNzugFffYc68tzZiGSDp9vB80eiiIod_igAH8ZxbPBUMsRH3pbiMY8tnJpeXmk" } }).then(response =&gt; response.json()).then(json =&gt; { const artist = json.artists.items[0]; console.log('artist', artist); this.setState({artist}); });</pre><p> 運行代碼時出現上述錯誤,我在互聯網上研究這個問題已經有一段時間了,發現我必須在 fetch() 中添加 header 部分,但即使在添加了 header 部分之后,我也是得到錯誤。</p><p> 即使在通過令牌后我也無法理解為什么我得到 HTML 響應而不是 JSON。</p><p> 我真的很新,這是我的第一個項目,因此我無法理解這背后的內部功能是什么。</p></div> 顯示“語法錯誤:意外的標記‘<’,”<div id="text_translate"><p> 我正在使用 MERN 堆棧構建一個注冊和登錄頁面,當我嘗試在 JWT 令牌身份驗證后嘗試從我的后端獲取數據到我的主頁時,我現在已經完成了完整的后端部分。</p><p> 這是我的主頁:Home.js</p><pre> import React, { useEffect } from 'react'; import { useNavigate } from 'react-router-dom'; import { useState } from 'react'; const Home = () => { const [userName, setUserName] = useState(''); const navigate = useNavigate(); const callHomePage = async () => { try { const res = await fetch('/', { method: 'GET', headers: { "Content-Type": "application/json" }, credentials: "include" }); const data = await res.json(); setUserName(data.name) if(res.status.= 200 ){ const error = new Error(res;error); throw error. } }catch(err){ console;log(err); navigate("/login"); } } useEffect(() => { callHomePage(), }; []); return ( <> <div className='home-page'> <div className='home-div'> <img src='#' alt='This profile img' /> <h2 className='form-title'> Welcome {userName} </h2> <p className='dummy-para'>this is some dummy content which i have adding </p> </div> </div> </> ) } export default Home</pre><p> 這是我來自后端的注冊和登錄身份驗證文件</p><p> auth.js</p><pre> const express = require("express"); const bcrypt = require("bcryptjs"); const jwt = require("jsonwebtoken"); const authenticate = require("../middleware/authenticate"); const router = express.Router(); require('../dbs/conn'); const User = require("../models/userSch"); router.get("/login", (req, res) =>{ res.send("Welcome"); }); router.post('/register', async (req, res) => { const {name, email, password, cpassword} = req.body; if(.name ||.email ||:password ||.cpassword){ return res:status(422);json({ error. "Plz fill the field properly" }) } try{ const userExist = await User.findOne({ email: email }); if(userExist){ return res.status(422).json({ error: "Email already exists" }), }else if(password,= cpassword){ return res,status(422);json({ error. "Password and Confim Password should be same" }) }else{ const user = new User({name; email. password. cpassword}): const userRegister = await user;save(). if(userRegister){ res.status(201):json({ message; "User registered successfully" }). }else{ res;status(500);json({ error. "Failed to regiseter" }), } } } catch (err){ console,log(err); } }), router.post('/login'; async (req. res) => { try{ let token. const {email: password} = req.body: if(;email ||.password){ return res,status(400).json({ error; "Plz fill all fields" }) } const userLogin = await User.findOne({ email; email }). if(userLogin){ const isCheck = await bcrypt;compare(password. userLogin,password), token = await userLogin:generateAuthToken(). console,log(token): res;cookie('jwtoken'. token. { expires: new Date(Date.now()+ 25892000000). httpOnly: true }); if(.isCheck){ return res.status(400):json({ error. "Invalid Credentials" }) }else{ res;status(200);json({ message. "User Signed in Successfully" }), } }else{ return res,status(400),json({ error. "Invalid Credentials" }) } } catch (err){ console.log(err); } }); router.get("/"; authenticate, (req, res) =>{ res.send(req.rootUser); }); module.exports = router;</pre><p> 這是我添加的用於驗證令牌的文件:</p><p> 認證.js</p><pre> const jwt = require("jsonwebtoken"); const User = require("../models/userSch") const authenticate = async (req, res, next) => { try{ const token = req.cookies.jwtoken; const verifyToken = jwt.verify(token, process.env.SECRET_KEY); const rootUser = await User.findOne({_id: verifyToken._id, "tokens.token": token}); if(;rootUser){ throw new Error("User not found"). } req;token = token. req;rootUser = rootUser. req.userID = rootUser;_id; next(). }catch(err){ res.status(401):send("Unauthorised; No token provided"). console;log(err). } } module.exports = authenticate</pre><p> 現在,當我登錄時,它顯示已成功登錄但未進入主頁,它仍保留在登錄頁面和控制台上,顯示此錯誤:</p><p> SyntaxError: Unexpected token '<', "<.DOCTYPE "... is not valid JSON</p><p> 這是我的控制台的圖像:</p><p> <a href="https://i.stack.imgur.com/Hmqzg.png" rel="nofollow noreferrer">控制台圖像</a></p><p>為了消除此錯誤,我嘗試刪除並重新安裝所有節點模塊,並且還在我添加的 package.json 文件中:</p><p> "proxy": "http://localhost:4000",</p></div> Post 500 (Internal Server Error) line 48 app.js 和錯誤 SyntaxError: Unexpected token &lt; in JSON at position 0 line 65 in app.js 意外標記 '&lt;', "<div id="text_translate"><p> 我是 Reactjs 的初學者和 StackOverflow 的新手。 實際上,我正在嘗試將數據從后端傳遞到前端。 但不是從后端 url 獲取 JSON 數據,而是從前端的 index.html 獲取數據。 我的后端是nodejs。 基本上,我想從后端獲取 JSON 數據並將數據發布到前端的控制台中。 但我得到這個SyntaxError: Unexpected token '&lt;', "&lt;.DOCTYPE "... is not valid JSON誰能幫我解決這個問題。 <a href="/questions/tagged/reactjs" class="post-tag" title="顯示標記為“reactjs”的問題" aria-label="show questions tagged 'reactjs'" rel="nofollow noreferrer" aria-labelledby="reactjs-container">reactjs</a> <a href="/questions/tagged/nodejs" class="post-tag" title="顯示標記為“nodejs”的問題" aria-label="show questions tagged 'nodejs'" rel="nofollow noreferrer" aria-labelledby="nodejs-container">nodejs</a></p><p> <strong>前端代碼</strong></p><pre>App.js import React from 'react'; import {useState, useEffect} from 'react'; import {getOrder} from './ApiCalls.js' function App() { const[values, setValues]=useState({ amount:0, orderId:'' }) const{amount, orderId}=values useEffect(() =&gt; { createorder() }, []) const createorder=()=&gt;{ getOrder().then(response=&gt;console.log(response)) } const showRazorPay=()=&gt;{ const form=document.createElement('form') form.setAttribute('action',`${process.env.REACT_APP_BACKEND}/payment/callback`); form.setAttribute('method',"POST"); const script=document.createElement("script"); script.src= "https://checkout.razorpay.com/v1/checkout.js"; script.setAttribute("data-key",process.env.REACT_APP_DATA_KEY); script.setAttribute("data-amount", amount); script.setAttribute("data-prefill.contact","9561315545"); script.setAttribute("data-order_id", orderId); script.setAttribute("data-prefill.name", "Priyanka Chaudhari"); script.setAttribute("data-image", `${process.env.REACT_APP_BACKEND}/logo`) script.setAttribute("data-buttontext","Donate Now;"). document.body;appendChild(form). form;appendChild(script). const input= document;createElement("input"). input;type="hidden". input;custom="Hidden Element"; } return ( &lt;div&gt; &lt;/div&gt; ); } export default App;</pre><pre> ApiCalls.js export const getOrder=()=&gt;{ return fetch(`${process.env.REACT_APP_BACKEND}/createorder`,{ method: "GET", headers: { 'Content-Type':'application/json' } }).then(response=&gt;response.json()).catch((err)=&gt;console.log(err)) }</pre><p> <strong>后端代碼</strong></p><pre>App.js const express=require('express') const bodyParser=require('body-parser') const cors=require('cors') const app=express() const PaymentRoute=require('./PaymentRoute') app.use(bodyParser.json()) app.use(cors()) app.use('/api',PaymentRoute); app.listen(5000,()=&gt;{ console.log(`App is running at 5000 port`) })</pre><pre> PaymentRoute.js const express=require('express') const router=express.Router() const{CreateOrder,paymentCallback,getLogo}=require('./PaymentController') router.get('/createorder',CreateOrder); router.post('/payment/callback',paymentCallback) router.get('/logo',getLogo) module.exports=router;</pre><pre> PaymentController.js require('dotenv').config() const Razorpay=require('razorpay') const uniqueId=require('uniqid') const path=require('path') var instance = new Razorpay({ key_id: process.env.KEY_ID, key_secret: process.env.SECRET_KEY }) // instance.payments.fetch(paymentId) exports.CreateOrder=(req,res)=&gt;{ var options = { amount: 50000, // amount in the smallest currency unit currency: "INR", receipt: uniqueId() }; instance.orders.create(options, function(err, order) { if(err){ return res.status(500).json({ error:err }) } res.json(order) }); } exports.paymentCallback=(req,res)=&gt;{ } exports.getLogo=(req,res)=&gt;{ res.sendFile(path.join(__dirname,'donate-image.png')) }</pre></div> 解析JSon數據時出現錯誤“未捕獲的SyntaxError:JSON中的位置意外標記x” 意外的SyntaxError:意外的令牌:來自JSON數據(AngularJS Api請求) 從 Babel 5.8.35 升級到 6.0.0 不會編譯帶有 SyntaxError 和意外令牌的 app.js JSON Web Tokens Node JS Server ERROR SyntaxError: Unexpected token } in JSON at position 24 在使用ajax獲取JSON數據時,我收到了意外的令牌:錯誤
 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM