React组件运行报错:Unexpected token '<' 求助
解决Node.js运行React组件时出现的SyntaxError: Unexpected token '<'错误
开发网站时使用Palm API生成AI试题,运行questionai2.js文件时持续出现以下错误:
<div> ^ SyntaxError: Unexpected token '<' at ESMLoader.moduleStrategy (node:internal/modules/esm/translators:119:18) at ESMLoader.moduleProvider (node:internal/modules/esm/loader:468:14) at async link (node:internal/modules/esm/module_job:68:21) Node.js v18.16.0
相关组件代码:
import React, { useEffect, useState } from 'react'; import { google } from 'googleapis'; import { TextServiceClient } from '@google-ai/generativelanguage'; import ReactDOM from 'react-dom/client'; const MODEL_NAME = "models/text-bison-001"; const API_KEY = "this would be my actual api key"; // Replace with your actual API key export const AiQuestionComponent = () => { const [questions, setQuestions] = useState([]); useEffect(() => { aiGeneratedQuestions().then((generatedQuestions) => { setQuestions(generatedQuestions); }); }, []); async function aiGeneratedQuestions() { console.log('in aiGeneratedQuestions'); const authClient = new google.auth.GoogleAuth({ credentials: { access_token: API_KEY, }, scopes: ['https://www.googleapis.com/auth/cloud-language'], }); const textServiceClient = new TextServiceClient({ authClient: await authClient.getClient(), }); const input = ' '; const promptString = `input: Write me an AP biology exam with the following guidelines: Exam Format The AP Biology Exam has question types and point values that remain stable and consistent from year to year, so you and your students know what to expect on exam day. Section II: Free Response 6 Questions | 1 hour 30 Minutes | 50% of Exam Score There are 2 long questions and 4 short questions. Long questions are worth 8–10 points each; short questions are worth 4 points each. The long questions ask students to: Interpret and evaluate experimental results Interpret and evaluate experimental results with graphing The short-answer questions assess students’ understanding of the following: Scientific investigation Conceptual analysis Analysis of a model or visual representation Data analysis stucture questions like this: 1. question here a) b) c) d) (questions 1 through 4) structure graphs like this: graph^ |colname1|colname2|colname3 |data1|data2|data3 |data4|data5|data6 input: ${input} output:`; const stopSequences = []; try { console.log('in try') const result = await textServiceClient.projects.locations.models.generateText({ parent: MODEL_NAME, requestBody: { input: promptString, model: MODEL_NAME, temperature: 0.7, maxTokens: 20000, stopSequences: stopSequences, }, }); if ( result[0] && result[0].candidates && result[0].candidates.length > 0 ) { console.log('after if') const generatedText = result[0].candidates[0].output || result[0].candidates[0].text; console.log(generatedText); const questions = generatedText .split(/\*\*(Long|Short) Question \d+\*\* \(\d+ points\)/) .filter((question) => question.trim() !== ''); const formattedQuestions = questions.map((question) => { const trimmedQuestion = question.trim(); if (trimmedQuestion.startsWith('Long')) { const subQuestions = trimmedQuestion .split(/(\d+\.\s+.+)/) .filter((subQuestion) => subQuestion.trim() !== ''); return subQuestions; } return trimmedQuestion; }); console.log('AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'); console.log(formattedQuestions); return formattedQuestions; } else { console.log('No generated text found.'); return []; } } catch (error) { console.error('Error:', error); return []; } } return ( <div> <h1>Generated Questions</h1> <ul> {questions.map((question, index) => ( <li key={index}> <p>{question}</p> </li> ))} </ul> </div> ); }; export default AiQuestionComponent;
问题原因
Node.js本身无法解析JSX语法,直接用node questionai2.js命令运行包含JSX的组件文件时,Node会将<div>这类JSX标签识别为无效的JavaScript语法,从而抛出Unexpected token '<'错误。
解决步骤
- 使用React脚手架运行项目:确保项目通过Create React App或类似React初始化工具创建,这类工具已内置Babel转译JSX语法。将
AiQuestionComponent正确引入App.js后,执行项目启动命令(如npm start)运行整个应用,而非单独执行组件文件。 - 避免前端硬编码密钥:不要在组件代码中直接写入
API_KEY,这会导致密钥泄露。可将密钥存入项目根目录的.env文件,通过process.env.REACT_APP_API_KEY读取(变量名需以REACT_APP_开头)。 - 解决跨域风险:当前代码直接在前端调用Palm API会触发浏览器跨域限制,建议通过后端代理处理API请求——前端向自身后端接口发送请求,再由后端调用Palm API并返回结果。
内容的提问来源于stack exchange,提问作者bonk
相关产品推荐
相关产品推荐

