-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
60 lines (50 loc) · 1.75 KB
/
server.js
File metadata and controls
60 lines (50 loc) · 1.75 KB
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
// No need to import fetch—Node v24.11.0 has native fetch support!
const express = require('express');
const app = express();
const PORT = 5050;
require('dotenv').config();
const API_KEY = process.env.PERPLEXITY_API_KEY;
// Debug: Print key at startup; remove or comment out when live!
console.log('Loaded API KEY:', API_KEY);
app.use(express.json());
// Open CORS for all origins (safe for local/test)
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Content-Type');
next();
});
app.post('/qna', async (req, res) => {
const question = req.body.question;
if (!question) {
return res.status(400).json({ error: 'No question provided' });
}
try {
const perplexityResponse = await fetch('https://api.perplexity.ai/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + API_KEY,
},
body: JSON.stringify({
model: "sonar",
messages: [{ role: "user", content: question }],
}),
});
if (!perplexityResponse.ok) {
const errorText = await perplexityResponse.text();
console.error("API Response Error: ", errorText);
return res.status(perplexityResponse.status).json({ error: errorText });
}
const data = await perplexityResponse.json();
const answer = data.answer ||
(data.choices && data.choices[0] && data.choices[0].message && data.choices[0].message.content) ||
'No answer received.';
res.json({ answer });
} catch (err) {
console.error("Catch Error: ", err);
res.status(500).json({ error: err.message });
}
});
app.listen(PORT, () => {
console.log(`Backend running on http://localhost:${PORT}`);
});