-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
70 lines (59 loc) · 2.46 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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
const http = require('http');
const fs = require("fs");
const path = require("path");
const formidable = require('formidable');
const translate = require('translate-platforms');
const github = 'https://github.com/imlinhanchao/translate-platform-api'
async function main() {
createServer();
}
async function createServer() {
let html = fs.readFileSync(path.join(__dirname, 'index.html'))
http.createServer(async function (request, response) {
if (request.method == 'POST') {
try {
response.writeHead(200, {
'Content-Type': 'application/json; charset=utf-8',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
'Access-Control-Allow-Credentials': 'true',
'Access-Control-Allow-Headers': 'Content-Type,Content-Length, Authorization, Accept,X-Requested-With'
});
const form = formidable({ multiples: true });
form.parse(request, async (err, fields, files) => {
let { platform, to, from, word } = fields;
if (!word || !platform || !to) return response.end(JSON.stringify({
status: 2,
msg: 'Parameter error!'
}));
try {
let data = await translate[platform](word, { to, from });
response.end(JSON.stringify({
status: 0,
msg: 'tranlate success',
data
}));
} catch (error) {
response.end(JSON.stringify({
status: 3,
msg: error.message
}));
}
});
} catch (error) {
response.end(JSON.stringify({
status: -1,
msg: `Has something wrong: ${error.message}. Please post a <a href="${github}/issues">Issue</a> to me.`
}));
console.error(error);
}
} else {
response.writeHead(200, {
'Content-Type': 'text/html; charset=utf-8',
});
response.end(html)
}
}).listen(8888);
console.info('Server running at http://localhost:8888/');
}
main();