简体   繁体   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"

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"

App.js应用程序.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 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;

I manually gave the api link in browser and got this result https://api.openweathermap.org/data/2.5/weather?lat=-27.47&lon=153.12&appid=<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}

While getting response instead of response getting error.在获得响应而不是响应时出现错误。 Not sure what i did wrong here.不确定我在这里做错了什么。

While getting response instead of response getting error.在获得响应而不是响应时出现错误。

From comment got suggestion how to get the whole response, Here what i got,从评论中得到了如何获得整个回复的建议,这是我得到的,

<!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>

There isn't any error related anything没有任何相关的错误

The issue seems to be here.问题似乎就在这里。

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

It should be -它应该是 -

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 - 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> - 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 Post 500 (Internal Server Error) line 48 app.js 和错误 SyntaxError: Unexpected token &lt; in JSON at position 0 line 65 in app.js - Post 500 (Internal Server Error) line 48 app.js and error SyntaxError: Unexpected token < 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> - Unexpected token '<', "<!DOCTYPE "... is not valid JSON 解析JSon数据时出现错误“未捕获的SyntaxError:JSON中的位置意外标记x” - While parsing JSon data getting Error “Uncaught SyntaxError: Unexpected token x in JSON at position” 意外的SyntaxError:意外的令牌:来自JSON数据(AngularJS Api请求) - Unexpected SyntaxError: Unexpected token : from JSON data (AngularJS Api Request) 从 Babel 5.8.35 升级到 6.0.0 不会编译带有 SyntaxError 和意外令牌的 app.js - Upgrading from Babel 5.8.35 to 6.0.0 will not compile app.js with a SyntaxError and unexpected token JSON Web Tokens Node JS Server ERROR SyntaxError: Unexpected token } in JSON at position 24 - JSON Web Tokens Node JS Server ERROR SyntaxError: Unexpected token } in JSON at position 24 在使用ajax获取JSON数据时,我收到了意外的令牌:错误 - While fetching JSON data using ajax i am getting Unexpected token : error
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM