简体   繁体   English

意外的标记“<”,“<div id="text_translate"><p> 在过去的几天里,我一直在尝试解决这个错误。 我非常困惑,因为我不知道为什么这不起作用。 任何帮助或建议将不胜感激。</p><p> 当我尝试在我的客户端 js 中从 node.js 获取数据时,我的 JSON 解析器给我一个错误:</p><pre> uncaught SyntaxError: Unexpected token '<', "<.DOCTYPE "... is not valid JSON at JSON.parse (<anonymous>) at XMLHttpRequest.onLoad (something:js:18:29)</pre><p> 为此,我使用了 node、js 和 html,总共 3 个文件。 这是 index.js:</p><pre> const express = require('express'); const app = express(); app.use(express.static('public')); app.use(express.json()); app.listen(3000, () => { console.log('server started'); }); app.get('/', function(req, res) { console.log('hello') }); app.listen(8080); var bodyParser = require('body-parser'); app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); app.post('/testing/thisshit', async function(req, res) { console.log(req.body); var dataToSendToClient = '{"message":"potatohead"}'; res.send(dataToSendToClient); });</pre><p> html:</p><pre> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> </head> <body> <div>hellow world</div> <script src="something.js"></script> </body> </html></pre><p> 客户端JS:</p><pre> console.log('testing') var abcd = {juice: "juice"} $.post( '/testing/thisshit', abcd); var res = new XMLHttpRequest(); var url = '/testing/thisshit'; res.open('GET',url,true); // set this to POST if you would like res.addEventListener('load',onLoad); res.addEventListener('error',onError); res.send(); function onLoad() { var response = this.responseText; console.log(response); var parsedResponse = JSON.parse(response); console.log("the result: " + parsedResponse) } function onError() { console.log('error'); }</pre><p> 无论我尝试什么,它似乎都让我感到困惑。 任何答案或建议都将非常有帮助,并提前感谢您提出任何建议。</p></div>

[英]Unexpected token '<', "<!DOCTYPE "... is not valid JSON. Utilizing express and parsing error. Any suggestions would be great

For the past few days, I have been attempting to solve this error.在过去的几天里,我一直在尝试解决这个错误。 I am extremely baffled, as I have no idea why this isn't working.我非常困惑,因为我不知道为什么这不起作用。 Any help or suggestions would be greatly appreciated.任何帮助或建议将不胜感激。

When I attempt to get data from node.js in my client side js, my JSON parser is giving me an error:当我尝试在我的客户端 js 中从 node.js 获取数据时,我的 JSON 解析器给我一个错误:

uncaught SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON
    at JSON.parse (<anonymous>)
    at XMLHttpRequest.onLoad (something.js:18:29)

I am using node, js, and html for this, 3 files total.为此,我使用了 node、js 和 html,总共 3 个文件。 Here is the index.js:这是 index.js:

const express = require('express');

const app = express();

app.use(express.static('public'));
app.use(express.json());
app.listen(3000, () => {
  console.log('server started');
});

app.get('/', function(req, res) {
  console.log('hello')
});
app.listen(8080);

var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());


app.post('/testing/thisshit', async function(req, res) {
  console.log(req.body);
  var dataToSendToClient = '{"message":"potatohead"}';
  res.send(dataToSendToClient);
});

The html: html:

<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  </head>
  <body>

<div>hellow world</div>

  <script src="something.js"></script>


</body>
</html>

The client-side JS:客户端JS:

console.log('testing')
var abcd = {juice: "juice"}
  $.post( '/testing/thisshit', abcd);
var res = new XMLHttpRequest();
var url = '/testing/thisshit';
res.open('GET',url,true); // set this to POST if you would like
res.addEventListener('load',onLoad);
res.addEventListener('error',onError);
res.send();
function onLoad() {
  var response = this.responseText;
  console.log(response);
  var parsedResponse = JSON.parse(response);
  console.log("the result: " + parsedResponse)
}
function onError() {
  console.log('error');
}

No matter what I attempt, it seems to baffle me.无论我尝试什么,它似乎都让我感到困惑。 Any answers or suggestions would be incredibly helpful, and thank you in advance for any suggestions.任何答案或建议都将非常有帮助,并提前感谢您提出任何建议。

Oh wow.哦哇。 hahaha my bad.哈哈哈我的错。 After 10 hours of a gruelling search trying to solve this, I finally solved this.经过 10 个小时的艰苦搜索试图解决这个问题,我终于解决了这个问题。

res.open('get') was supposed to be res.open('post') . res.open('get')应该是res.open('post')

意外标记 '&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

显示“语法错误:意外的标记‘<’,”<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

从 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"

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 意外标记 '&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 显示“语法错误:意外的标记‘<’,”<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 从 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" 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 解析有效的JSON时出现&#39;Uncaught SyntaxError:Unexpected token:&#39; - 'Uncaught SyntaxError: Unexpected token :' when parsing valid JSON “语法错误:意外的标记 &#39;:&#39;。解析错误。” JSON 和 ajax - "SyntaxError: Unexpected token ':'. Parse error." JSON & ajax 意外的令牌/ JSON中。 如何在JSON数组中包含正则表达式? - Unexpected token / in JSON. How to include a regex in an array in a JSON? Javascript - JSON.parse:意外的数据结束 - 使用有效JSON时出错。 我究竟做错了什么? - Javascript - JSON.parse: unexpected end of data - Error when using valid JSON. What am I doing wrong? Browserify Express应用程序错误:分析文件意外令牌 - Browserify Express App Error: Parsing file Unexpected token 解析错误:意外的令牌 - Parsing Error: Unexpected token
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM