简体   繁体   中英

Express.js Server: PUT Request using Middleware

I have a working Node/Express server and I'm using it to do requests via localhost to an external API. As you can see in my example code, I'm using node-fetch for my basic GET requests.

For every request, I prepare a const url = BASE_URL in advance, needed for the actual external server request.

But I'm getting stuck at my PUT-Request as I can't using node-fetch . So what do I have to do, to notify my Express server with the actual URL for the PUT-Request?

The PUT-Request doesn't work til here.

/* Route: Get Appointment it's availability times */
app.get('/availability/times/:id/:date/:locationId', (req, res) => {
  var id = req.params.id;
  var date = req.params.date;
  var locationId = req.params.locationId;
  const url = BASE_URL + '/availability/times?appointmentTypeID=' + id + '&date=' + date + '&calendarID=' + locationId;;
  fetch(url, {
      mode: "no-cors",
      method: "GET",
      headers: {
        'Content-Type': 'application/json',
        'X-Requested-With': 'content-type'
      },
    })
    .then(response => response.json())
    .then(json => {
      res.json(json);
    });
});

app.put('/appointments/:id/cancel', (req, res) => {
  var id = req.params.id;
  const url = BASE_URL + '/appointments/' + id + '/cancel';
  res.send(req.body)
});

If you're saying that fetch is undefined in your put request, make sure you are requiring it at the top before any routes var fetch = require('node-fetch') . For your base url, you should store that in a config file. Create a file called config.js that looks something like this:

module.exports = {
  'BASE_URL': 'yoururlhere'
}

then require this in your express server var config = require('pathToConfig'); and you can use it by specifying config.BASE_URL

If that doesn't help, please be more specific with what your actual problem is

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM