-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.js
executable file
·48 lines (40 loc) · 1.04 KB
/
index.js
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
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const morgan = require('morgan');
const translate = require('google-translate-api');
const app = express();
const port = 3000;
app.use(cors());
app.use(morgan('combined'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.get('/', (req, res) => {
const help = `
<pre>
Welcome to the Server Google Translate API!
The following endpoint is available:
POST /translate { text, from, to }
</pre>
`;
res.send(help);
});
app.post('/translate', (req, res) => {
const { text, from, to } = req.body;
if (text && to) {
translate(text, { from, to }).then(data => {
res.send({ 'text': data.text });
}).catch(error => {
console.error(error);
res.status(500).send(error);
});
}
else {
res.status(403).send({
error: 'Please provide a "text" and "to" in the request body'
});
}
});
app.listen(port, () => {
console.log(`Listening on port ${port}`);
});