-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
76 lines (70 loc) · 2.64 KB
/
Copy pathindex.js
File metadata and controls
76 lines (70 loc) · 2.64 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
const http = require('http');
const url = require('url');
const { parse } = require('querystring');
const fs = require('fs');
const path = require('path');
const db = require('./db');
const Notes = db.notes;
const randomstring = require("randomstring");
http.createServer((req, res) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
res.setHeader('Access-Control-Allow-Credentials', true);
console.log('server work ========');
if (req.method == 'GET') {
res.end('server work nodeJS');
}
else {
// POST Method
let body = '';
req.on('data', chunk => {
body += chunk.toString();
});
req.on('end', () => {
let params = JSON.parse(body);
res.writeHead(200, { "Content-Type": "application/json" });
if (params.note) {
let note = params.note;
note = note.trim();
// console.log(note);
Notes.create({
url: randomstring.generate({
length: 24,
capitalization: 'lowercase'
}),
text: note,
timestamp: Math.floor(Date.now() / 1000),
}).then(result => {
res.end(JSON.stringify({ 'result': true, "url": result.url }));
}).catch(err => {
// console.log(err);
res.end(JSON.stringify({ 'result': false, "error": err }));
});
}
else if (params.url) {
let url = params.url;
url = url.trim();
// console.log(url);
Notes.findOne({
where: {
"url": url
}
})
.then(result => {
if (result) {
res.end(JSON.stringify({ 'result': true, "note": result.text }));
// Notes.destroy({where: {id: result.id}}); // if you want delete message!!!
}
else {
res.end(JSON.stringify({ 'result': false, "text": 'note not found' }));
}
})
.catch(err => {
// console.log(err);
res.end(JSON.stringify({ 'result': false, "error": err }));
});
}
});
}
}).listen(3500);