Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/35.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Express.js http调用内部路由不';t更新变量_Javascript_Node.js_Http_Express_Request - Fatal编程技术网

Javascript Express.js http调用内部路由不';t更新变量

Javascript Express.js http调用内部路由不';t更新变量,javascript,node.js,http,express,request,Javascript,Node.js,Http,Express,Request,我正在express.js之上构建一个RESTAPI。我在更新路由中的变量时遇到问题 例如: 我正在调用app.get(“/wp/page/create/:id”),函数(req,res) 在这个路由中,我首先使用request promiselibrary调用一个http请求。我在嵌套的http调用中使用这个调用的响应 我使用一个全局变量作为嵌套调用的头,我需要使用etag变量对头a进行更改 global.postHeaders = headers; postHeaders['X-HTTP-M

我正在express.js之上构建一个RESTAPI。我在更新路由中的变量时遇到问题

例如:

我正在调用
app.get(“/wp/page/create/:id”),函数(req,res)

在这个路由中,我首先使用
request promise
library调用一个http请求。我在嵌套的http调用中使用这个调用的响应

我使用一个全局变量作为嵌套调用的头,我需要使用
etag
变量对头a进行更改

global.postHeaders = headers;
postHeaders['X-HTTP-Method'] = "MERGE";
postHeaders['Content-Type'] = 'application/json;odata=verbose';
postHeaders['X-RequestDigest'] = spContext;

request.get({
 url: "xxx",
 headers: headers,
 json: true
 }).then(function(response) {
var etag = response.d.__metadata.etag
postHeaders['If-Match'] = etag;

   request.post({
     url: "xxx",
     type: "POST",
     body: data,
     headers: postHeaders,
     json: true
     }).then(function(data) {
      postHeaders['If-Match'] = "";
      res.send(data).end()
      console.log("All done!");
  })
})
代码:

当我启动服务器并输入路由时,一切正常。当我再次尝试点击它时,
etag
变量仍然相同,即使它应该更新

如果我重新启动服务器,它会在第一次尝试时再次工作,但在第二次/第三次尝试时失败


知道我做错了什么吗?

我已经解决了问题。简单的解决方案是清除包含变量的标题

global.postHeaders = headers;
postHeaders['X-HTTP-Method'] = "MERGE";
postHeaders['Content-Type'] = 'application/json;odata=verbose';
postHeaders['X-RequestDigest'] = spContext;

request.get({
 url: "xxx",
 headers: headers,
 json: true
 }).then(function(response) {
var etag = response.d.__metadata.etag
postHeaders['If-Match'] = etag;

   request.post({
     url: "xxx",
     type: "POST",
     body: data,
     headers: postHeaders,
     json: true
     }).then(function(data) {
      postHeaders['If-Match'] = "";
      res.send(data).end()
      console.log("All done!");
  })
})

postHeaders是一个全局变量。
global.postHeaders=headers;
中的headers也是一个全局变量吗?无论您在这里做什么都是大错特错的。postHeaders变量将在多个请求中共享。因此,您将遇到一种情况,
postHeaders['If-Match']
值可能是空字符串或etag

试试这个而不是第一行
var postHeaders=Object.assign({},headers);

不确定您正在尝试什么,但至少此语句将消除代码中的巨大错误。这将为每个请求创建一个新的头对象