帮我写一个后端调通前端的AI对话页面的代码,前端技术为Vue,后端技术为Java,框架为sprinboot
时间: 2024-02-16 08:03:43 浏览: 152
好的,以下是一个简单的示例代码:
1. 首先在后端中创建一个接口,用于接收前端发送的对话请求,并将请求发送到AI对话的API中进行处理,并返回对话结果给前端。示例代码如下:
```
@RestController
@RequestMapping("/api/chat")
public class ChatController {
@Autowired
private RestTemplate restTemplate;
private static final String AI_API_URL = "https://api.ai.com/chat";
@PostMapping
public String chat(@RequestBody String question) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
JSONObject request = new JSONObject();
request.put("question", question);
HttpEntity<String> entity = new HttpEntity<>(request.toString(), headers);
ResponseEntity<String> response = restTemplate.postForEntity(AI_API_URL, entity, String.class);
if (response.getStatusCode() == HttpStatus.OK) {
JSONObject result = new JSONObject(response.getBody());
return result.getString("answer");
} else {
return "Error";
}
}
}
```
2. 在前端中,创建一个Vue组件用于显示对话框,并发送对话请求到后端。示例代码如下:
```
<template>
<div class="chat-container">
<div class="chat-history">
<div class="chat-message" :class="{ 'chat-message-left': !message.isMe }" v-for="message in messages" :key="message.id">
<div class="chat-message-content">
<div v-if="message.isMe" class="chat-message-text chat-message-text-me">{{ message.text }}</div>
<div v-else class="chat-message-text">{{ message.text }}</div>
</div>
</div>
</div>
<div class="chat-input">
<input type="text" v-model="inputText" @keydown.enter="sendMessage" placeholder="输入您的问题" />
</div>
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
messages: [],
inputText: ''
};
},
methods: {
sendMessage() {
const question = this.inputText.trim();
if (question.length === 0) {
return;
}
this.messages.push({ id: Date.now(), text: question, isMe: true });
this.inputText = '';
axios.post('/api/chat', question).then(res => {
const answer = res.data;
this.messages.push({ id: Date.now(), text: answer, isMe: false });
});
}
}
};
</script>
```
这个示例代码中使用了axios库来发送POST请求到后端API,并将返回的对话结果显示在前端页面。请注意,在实际使用中需要将`/api/chat`替换为你实际的后端API地址。
阅读全文