DeanPaul / blog

MIT License
2 stars 1 forks source link

set up a simple REST server in Node.js #26

Open DeanPaul opened 6 years ago

DeanPaul commented 6 years ago

Create a Node project

npm init

Set up an Express Node server

Install Express

npm install express --save-dev

Start server

package.json

"scripts": {
    "start": "node index.js",
    "debug": "node debug index.js"
  },

create index.js

const express = require('express');
const app = express();
app.get('/', (request, response) => response.send('Hello World'));
app.listen(3000, () => console.log('Listening on port 3000'));

npm run start

Add Router

npm install --save body-parser

const express = require('express');
const app = express();
const router = express.Router();
const port = 3000;
const bodyParser = require('body-parser');

app.use(bodyParser.urlencoded());
app.use(bodyParser.json());
app.get('/', (request, response) => response.send('Hello World'));

app.use('/api', router);

router.get('/', (request, response) => {
  response.json({message: 'Hello, welcome to my server'});
});

app.listen(port, () => console.log(`Listening on port ${port}`));

router.get('/test', (request, response) => {
  response.json({message: "test request"});
});
router.post('/test', function (request, response) {
    debugger;
    console.log(request.body);
    res.json({message: request.body});
});
DeanPaul commented 6 years ago

postman 1 header

2 body 3

DeanPaul commented 6 years ago

curl -X POST -H "Content-Type: application/json" -H "Cache-Control: no-cache" -H "Postman-Token: cbc7893b-f2b6-1aeb-b39f-4c32c948baf5" -d '{"a":2}' "http://localhost:3000/api/test"

DeanPaul commented 6 years ago
var data = JSON.stringify({
  "a": 2
});

var xhr = new XMLHttpRequest();
xhr.withCredentials = true;

xhr.addEventListener("readystatechange", function () {
  if (this.readyState === 4) {
    console.log(this.responseText);
  }
});

xhr.open("POST", "http://localhost:3000/api/test");
xhr.setRequestHeader("content-type", "application/json");
xhr.setRequestHeader("cache-control", "no-cache");
xhr.setRequestHeader("postman-token", "c3d5657c-a802-c9cc-6129-c56d0ef74b74");

xhr.send(data);