Chrome扩展调用本地Ollama API遭遇403禁止错误求助
解决Chrome扩展调用本地Ollama API出现403 Forbidden错误的方案
1. 修正Chrome扩展权限配置
Manifest V3中,跨域请求权限仅需在host_permissions中声明,permissions字段不需要重复添加URL规则。修改你的manifest.json,删除permissions里的"http://localhost:11434/*"和"http://127.0.0.1:11434/*",避免冗余:
{ "manifest_version": 3, "name": "Codegenerator", "description": "A Codegenerator", "version": "1.0", "permissions": [ "tabs", "activeTab", "<all_urls>", "scripting" ], "host_permissions": ["http://localhost:11434/*", "http://127.0.0.1:11434/*"], "action": { "default_popup": "index.html", "default_icon": "logo.png" } }
修改后务必在chrome://extensions/页面点击扩展卡片的刷新按钮,重新加载扩展使配置生效。
2. 配置Ollama允许Chrome扩展的跨域请求
Ollama默认的CORS策略会拦截非原生本地环境的请求,Chrome扩展属于独立的浏览器上下文,需要添加到Ollama的允许来源列表:
- 找到或创建Ollama的配置文件:
- Windows:
%USERPROFILE%\.ollama\config.json - macOS/Linux:
~/.ollama/config.json
- Windows:
- 在配置文件中添加
origins字段,允许所有Chrome扩展的请求:
{ "origins": ["chrome-extension://*"] }
- 重启Ollama服务:
- Windows:打开任务管理器结束Ollama进程后重新启动
- macOS:执行命令
brew services restart ollama - Linux:执行命令
sudo systemctl restart ollama
3. 完善fetch请求的参数
你的请求缺少Content-Type头,并且可以简化JSON解析逻辑,修改后的调用函数如下:
function generateCodeSuggestionFromOllama(prompt) { const apiUrl = `http://localhost:11434/api/generate`; const body = { "model": "codellama", "prompt": prompt, "stream": false, }; fetch(apiUrl, { method: 'POST', headers: { 'Content-Type': 'application/json', // 新增请求头 }, body: JSON.stringify(body), }) .then(response => { console.error(`请求状态: ${response.status} ${response.statusText}`); if (!response.ok) { throw new Error(`请求失败: ${response.status} ${response.statusText}`); } return response.json(); // 直接解析JSON,无需先转文本 }) .then(jsonData => { console.log(jsonData); const response = jsonData.response; document.getElementById("codeSuggestion").innerHTML = response; }) .catch(error => { console.error('处理请求时出错:', error); // 这里可以添加用户友好的错误提示 }) }
4. 验证Ollama服务的可用性
先在浏览器地址栏访问http://localhost:11434/api/tags,如果返回包含模型列表的JSON,说明服务运行正常;如果无法访问,检查Ollama是否确实在11434端口启动。
内容的提问来源于stack exchange,提问作者DevChris
相关产品推荐
相关产品推荐

