如果你有这个需求可以参考 ollama 的官方api与本篇文章,官方的例子里很多都是用了curl进行演示。
https://github.com/ollama/ollama/blob/main/docs/api.md
在写脚本之前需要先确认本地的 ollama 网络服务是否正常启动。
http://localhost:11434 通过访问本机的11434端口确定是否ollama的服务正常运行
值得注意的是在浏览器中访问本地 index.html 文件时,一般会遇到 CORS(跨源资源共享)策略限制,导致无法调用本地的 Ollama API,所以你需要在本地搭建一个http服务器,如果没有这个服务器的话,可以使用下面这个VSCode插件。

右键你的html文件启动本地http服务器,现在就可以很方便的调试你的页面,好用推荐。
既然我们已经拿到了官网的API文档,那么下面要做的事很简单,将这个文档丢给deepseek,或者是其他的ai,让打工ai给我们造一个前端界面就用。

分析下核心代码,参考了文档中使用curl发送json的测试用例,写了一个post方式提交数据到特定的地址。

参考代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
| <!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>与 Ollama 交互</title> <style> body { font-family: Arial, sans-serif; } #messages { border: 1px solid #ccc; padding: 10px; max-height: 300px; overflow-y: auto; } #inputMessage { width: 100%; padding: 10px; margin-top: 10px; box-sizing: border-box; } #sendButton { margin-top: 10px; padding: 10px 20px; background-color: #4CAF50; color: white; border: none; cursor: pointer; } #sendButton:hover { background-color: #45a049; } </style> </head> <body> <h1>与 Ollama 交互</h1> <div id="messages"></div> <textarea id="inputMessage" placeholder="输入你的消息..." rows="3"></textarea> <button id="sendButton">发送</button>
<script> const sendButton = document.getElementById('sendButton'); const inputMessage = document.getElementById('inputMessage'); const messages = document.getElementById('messages');
const ollamaApiUrl = 'http://localhost:11434/api/chat';
sendButton.addEventListener('click', async () => { const message = inputMessage.value.trim(); if (!message) return;
addMessage('你:' + message);
try { const response = await fetch(ollamaApiUrl, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ model: 'deepseek-r1:8b', messages: [ { role: 'user', content: message } ], stream: false }) });
if (response.ok) { const data = await response.json(); const reply = data.message && data.message.content ? data.message.content : '无回复内容'; addMessage('Ollama:' + reply); } else { addMessage('错误:无法与 Ollama 服务通信'); } } catch (error) { addMessage('错误:' + error.message); }
inputMessage.value = ''; });
function addMessage(text) { const messageDiv = document.createElement('div'); messageDiv.textContent = text; messages.appendChild(messageDiv); messages.scrollTop = messages.scrollHeight; } </script> </body> </html>
|
以上,记录通过js调用ollama的api。
本文标题:通过js调用ollama的api
文章作者:Keyle
发布时间:2025-02-18
最后更新:2025-02-18
原始链接:https://vrast.cn/posts/13797/
版权声明:©Keyle's Blog. 本站采用署名-非商业性使用-相同方式共享 4.0 国际进行许可