在节点后端中使用客户端API回调的变量



如果我使用下面的代码在客户端提出请求

public/foo.js

function bar() {
  fetch('https://api.github.com/')
    .then(response => response.json())
    .then(data => {
      console.log(data)
    })
    .catch(error => console.error(error))
}

如何将data变量发送到节点后端?

/app.js

app.get("/", cors(), (request, response) => {
  response.render('index.html');
})

我的理解是,您正在尝试从URL获取服务器端在客户端上未处理的数据,并将该数据发送回您自己的服务器端。

在您的服务器端,创建一个新帖子方法:

app.post("/example", cors(), (request, response) => {
  let body = request.body;
  response.json(body);
})

在您的客户端,发送新的帖子请求:

function postExample(data) {
  return fetch(`http://localhost:YOURPORT/example`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(data)
  });
}

用服务器的端口替换YOURPORT。并致电postExample

function bar() {
  fetch('https://api.github.com/')
    .then(response => response.json())
    .then(data => {
      postExample(data).then(res => res.json())
                       .then(console.log(res));
    })
    .catch(error => console.error(error))
}

最新更新