This repository has been archived by the owner on Aug 15, 2023. It is now read-only.
forked from ahandsel/React_Workshop_by_Kintone
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathserver.js
82 lines (69 loc) · 2.44 KB
/
server.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
71
72
73
74
75
76
77
78
79
80
81
82
// backend - server.js - Routes API requests from the frontend to Kintone
// Express Server Setup
const express = require('express');
const cors = require('cors');
const fetch = require('node-fetch');
const PORT = 5000;
const app = express();
// Hide sensitive info in a .env file with dotenv
require('dotenv').config();
// Get Kintone credentials from a .env file
const subdomain = process.env.SUBDOMAIN;
const appID = process.env.APPID;
const apiToken = process.env.APITOKEN;
// Parse incoming requests with JSON payloads
app.use(express.json());
// Set Cross-Origin Resource Sharing (CORS) to frontend React App
app.use(cors());
const corsOptions = {
origin: 'http://localhost:3000'
};
// Append a query parameter to the request endpoint
// This query orders records by their Record_number in ascending order
const parameters = 'query=order by Record_number asc';
// Kintone's record(s) endpoints
const multipleRecordsEndpoint = `https://${subdomain}.kintone.com/k/v1/records.json?app=${appID}&${parameters}`
const singleRecordEndpoint = `https://${subdomain}.kintone.com/k/v1/record.json?app=${appID}`;
// This route executes when a GET request lands on localhost:5000/getData
app.get('/getData', cors(corsOptions), async (req, res) => {
const fetchOptions = {
method: 'GET',
headers: {
'X-Cybozu-API-Token': apiToken
}
}
const response = await fetch(multipleRecordsEndpoint, fetchOptions);
const jsonResponse = await response.json();
res.json(jsonResponse);
});
/* Add a new route for a POST request using singleRecordEndpoint in the section below */
// - - - - - - - START - - - - - - - -
// This runs if a POST request calls for localhost:5000/postData
app.post('/postData', cors(corsOptions), async (req, res) => {
const requestBody = {
'app': appID,
'record': {
'title': {
'value': req.body.title
},
'author': {
'value': req.body.author
}
}
};
const options = {
method: 'POST',
headers: {
'X-Cybozu-API-Token': apiToken,
'Content-Type': 'application/json',
},
body: JSON.stringify(requestBody)
}
const response = await fetch(singleRecordEndpoint, options);
const jsonResponse = await response.json();
res.json(jsonResponse);
});
// - - - - - - - END - - - - - - - -
app.listen(PORT, () => {
console.log(`\n Backend server listening at http://localhost:${PORT} \n Confirm if Kintone records are being retrieved at \n http://localhost:${PORT}/getData`);
});