javascript - Express.js 服务器:使用中间件的 PUT 请求
问题描述
我有一个可用的 Node/Express 服务器,我正在使用它通过 localhost 向外部 API 发出请求。正如您在我的示例代码中看到的那样,我正在使用node-fetch
我的基本 GET 请求。
对于每个请求,我都会const url = BASE_URL
提前准备一个实际外部服务器请求所需的。
但我被困在我PUT-Request
的,因为我无法使用node-fetch
. 那么我该怎么做才能用 PUT-Request 的实际 URL 通知我的 Express 服务器?
PUT-Request 在这里不起作用。
/* 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)
});
解决方案
如果您说fetch
在您的 put 请求中未定义,请确保您在任何 routes 之前都需要它var fetch = require('node-fetch')
。对于您的基本网址,您应该将其存储在配置文件中。创建一个名为的文件config.js
,如下所示:
module.exports = {
'BASE_URL': 'yoururlhere'
}
然后在您的快递服务器中要求它,var config = require('pathToConfig');
您可以通过指定来使用它config.BASE_URL
如果这没有帮助,请更具体地说明您的实际问题是什么
推荐阅读
- list - 如何访问在映射的键值对中作为值存在的列表元素,其中映射存在于 Dart 的另一个列表中
- stripe-payments - Localizing Stripe Payment on Sylius
- vue.js - vuejs - Create detached css file from apps.css
- c# - 如何在一个命令中增加大于 1 的整数值?
- c++ - 如何在 C++ 中访问对的集合
- java - 杰克逊中用于枚举的自定义 xml 反序列化器
- java - 在同一方法中同步多个块
- php - 验证失败时出现未找到错误
- javascript - Javascript字符串与变量值差异
- javascript - Aws dynamodb 错误错误 [UnknownError]:未找到 (aws-sdk)