首页 > 解决方案 > 如何将来自 POST 请求的 JSON 发送到客户端?

问题描述

我有一个运行 express 的节点服务器,它监听传入的请求。我正在渲染一个 HTML 文件,当我在我的服务器中收到一个 GET 请求时我想更新它。但是,当外部事件发生(异步)时,发送到我的服务器的数据是由 API 发送的。我不知道如何使用传入请求的 JSON 内容更新我提供的 HTML 文件。特别是,我正在尝试替换传入类的 inner.HTML 内容,正如您在我的代码中看到的那样。

我曾尝试在客户端使用 fetch API 向服务器发出请求以检索此数据,但它似乎不起作用。

服务器.js

const bodyParser = require('body-parser');
const port = 3000;

const app = express();
const server = app.listen(port, () => console.log('App listening on port ${port}'));

app.set('view engine', 'html');
app.engine('html', ejs.renderFile);

app.use(express.static(__dirname + '/public'));

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended:true}));



app.get (‘/incoming', (req,res)=>{

  const { status} = req.url;

  res.json(status);
  console.log(status);

}) ```

Client.js

fetch('http://localhost:3000/incoming').then(function(response) {
  return response.json();
}).then(response => {
  document.getElementById("dlr").innerHTML = response
}).catch(error => console.error(error))


index.html

 <!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/css-layout/1.1.1/css-layout.js" />
  <title>Node SMS Texting</title>
</head>
<body>
  <div class="container">
    <h2>Text API</h2>
    <input type="sender" name="from" id="from" placeholder="Enter sender ID ...">
    <input type="button" id="button" value="Send Text" class="button button-primary">
    <p class="response"></p>
    <p class="incoming"></p>
  </div>

  <script src="js/client.js"></script>
</body>
</html> 

I get the result logged in the console as per my console.log in the server side, but the client doesn't receive anything. This is the console.log


/incoming?user=A&to=Me&code=21404&Id=150000001A01F77B&&timestamp=2019-04-08+15%3A57%3A15&timestamp=1554739095&nonce=59167e2f-654c-4dd5-b236-bff9ac97f917

The only thing I see happening on the client side is /incoming set as text  set under the incoming.innerhtml class, but not the content of the GET request sent to my server.

Any help here would be highly appreciated.

Thanks in advance.

Regards,
Javier

标签: javascriptnode.jsapiexpressfetch

解决方案


您正在向 POST 端点发送 GET 请求。您可以通过在客户端的 fetch 中传递正文和方法来解决此问题。此外,您应该在响应返回时对其进行处理。将您的 fetch 重写为这样的内容。

fetch('http://localhost:3000/incoming', {
  method: 'post',
  body: JSON.stringify(body)
}).then(response => {
  document.getElementById("incoming").innerHTML = response
}).catch(error => console.error(error))

推荐阅读