<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>文心一言接口示例</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
}
#response {
margin-top: 20px;
padding: 10px;
border: 1px solid #ccc;
background-color: #f9f9f9;
}
#error {
color: red;
margin-top: 20px;
}
</style>
</head>
<body>
<h1>文心一言接口示例</h1>
<form id="queryForm">
<label for="query">请输入问题:</label>
<input type="text" id="query" name="query" required>
<button type="submit">提交</button>
</form>
<div id="response"></div>
<div id="error"></div>
<script>
document.getElementById('queryForm').addEventListener('submit', function(event) {
event.preventDefault();
const query = document.getElementById('query').value;
document.getElementById('response').textContent = '';
document.getElementById('error').textContent = '';
fetch('/ask', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ query: query }),
})
.then(response => response.json())
.then(data => {
if (data.error) {
document.getElementById('error').textContent = data.error;
} else {
document.getElementById('response').textContent = data.response;
}
})
.catch(error => {
document.getElementById('error').textContent = '请求失败: ' + error.message;
});
});
</script>
</body>
</html>
const express = require('express');
const bodyParser = require('body-parser');
const axios = require('axios');
const app = express();
const port = 3000;
app.use(bodyParser.json());
app.use(express.static('public'));
app.post('/ask', async (req, res) => {
const query = req.body.query;
try {
const response = await axios.post('https://api.wenxinyiyan.baidu.com/your-api-endpoint', {
// 填写必要的API请求参数
query: query,
// 其他API参数
}, {
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer your-api-key', // 替换为您的API密钥
},
});
res.json({ response: response.data.result });
} catch (error) {
res.json({ error: error.message });
}
});
app.listen(port, () => {
console.log(`服务器运行在 http://localhost:${port}`);
});
使用步骤:
- 替换占位符:在后端代码中,将
your-api-endpoint
和your-api-key
替换为您从百度文心一言获得的实际API端点和API密钥。 - 启动服务器:保存后端代码为
server.js
,并确保您已经安装了Node.js和Express。使用以下命令启动服务器:npm install express body-parser axios node server.js
- 打开HTML页面:将HTML代码保存为
index.html
,放在public
文件夹中。打开浏览器访问http://localhost:3000
,即可看到前端页面。 -
这样,用户输入问题后,前端会将问题发送到后端,后端请求百度文心一言API获取回答并将结果返回给前端,前端再显示结果给用户。