React集成Google Bard API遇CORS及Cookie验证问题求助
Google Bard API集成React前端问题排查
问题描述
将Google Bard API集成到React前端时遇到以下问题:
- Postman调用后端API可返回正确结果,但前端通过Fetch调用时先出现CORS问题
- 按提示配置
__Secure-1PSIDCookie,并在Express后端配置CORS后,仍出现解析错误及TypeError
提问界面:

Postman API响应正常
相关代码
后端Express代码
import { createRequire } from 'module'; const require = createRequire(import.meta.url); var express = require('express'); var bodyParser = require('body-parser'); var cors = require('cors'); import {Bard} from "googlebard"; var port = process.env.PORT || 5000; var app = express(); app.use(express.json()); app.use(cors({ origin: "*", methods: ["GET", "POST"] })); app.post ("/bard",async (req,res)=>{ res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); try{ let cookies = `__Secure-1PSID=ZQjuqQs64mhZLUGRh9Ma61gcl-hfONOEfUZNQeuehLXK5syPKzJL9sfkMbCv-i-zZJKS-A.` const bot = new Bard(cookies); let response = await bot.ask(req.body.prompt); res.status(200).json({"message":response}); }catch(err){ console.log(err); } }); app.listen(port, ()=>{ console.log("Server running at "+port); })
前端React代码
import logo from './logo.svg'; import './App.css'; import React, { useState, useEffect } from "react"; function App() { const [prompt, setPrompt] = useState(""); const [message, setMessage] = useState(""); const requestOption = { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ prompt: prompt }) } const fetchdata = () => { fetch("http://localhost:5000/bard", requestOption) .then((res) => res.json()) .then((data) => { console.log(data.message); setMessage(data.message); }); } const handleSubmit = (e) => { fetchdata(); } useEffect((e) => { handleSubmit(e); }, []); return ( <div className="App"> <form > <input name="prompt" className="form-control input-inline" type="text" placeholder='Ask anything' onChange={(e) => setPrompt(e.target.value)} /> <button type="submit" className="ask-button btn btn-primary" onClick={handleSubmit}>Ask</button> </form> <div id="answer" >{message}</div> </div> ); } export default App;
控制台报错信息
Error parsing response: make sure you are using the correct cookie, copy the value of "__Secure-1PSID" cookie and set it like this: new Bard("__Secure-1PSID=<COOKIE_VALUE>") Also using a US proxy is recommended. If this error persists, please open an issue on github. https://github.com/PawanOsman/GoogleBard TypeError: Cannot read properties of undefined (reading '3') at Bard.ask (file:///C:/Users/User1/google-bard-backend/node_modules/googlebard/dist/classes/bard.js:174:23) at process.processTicksAndRejections (node:internal/process/task_queues:95:5) at async file:///C:/Users/User1/google-bard-backend/app.js:27:24
问题排查与解决方案
1. Cookie有效性验证
- 重新获取
__Secure-1PSID:打开Google Bard官网并登录,通过开发者工具(F12)的Application标签→Cookies,复制完整的__Secure-1PSID值(确保无空格或多余字符) - 检查Cookie是否过期:Google会话Cookie会定期失效,需重新获取最新值
- 配置地区代理:后端服务器需使用美国地区代理,否则可能无法正常请求Bard API
2. 前端代码修正
- 移除自动调用的
useEffect:组件挂载时prompt为空,会触发无效的Bard请求,仅保留按钮点击触发逻辑 - 阻止表单默认提交行为:避免页面刷新,修改
handleSubmit:const handleSubmit = (e) => { e.preventDefault(); fetchdata(); } - 完善前端错误处理:避免请求失败时崩溃,增加catch逻辑:
const fetchdata = () => { fetch("http://localhost:5000/bard", requestOption) .then((res) => { if (!res.ok) throw new Error('请求失败'); return res.json(); }) .then((data) => { console.log(data.message); setMessage(data.message); }) .catch(err => { console.error('请求错误:', err); setMessage('请求失败,请稍后重试'); }); }
3. 后端代码优化
- 移除重复CORS配置:已通过
app.use(cors())全局配置,删除路由内的res.header代码,避免冲突 - 完善错误响应:给前端返回错误信息,避免前端无有效JSON解析:
catch(err){ console.log(err); res.status(500).json({error: err.message}); }
内容的提问来源于stack exchange,提问作者codegiver
相关产品推荐
相关产品推荐

