如何将来自POST请求的JSON发送到客户端?

时间:2019-04-05 14:06:41

标签: javascript node.js api express fetch

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

我尝试使用客户端上的访存API向服务器发出请求以检索此数据,但这似乎不起作用。

Server.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

1 个答案:

答案 0 :(得分:0)

您正在将GET请求发送到POST端点。您可以通过在客户端获取中传递主体和方法来解决此问题。另外,您应该在响应返回时进行处理。将您的抓取重写为类似以下内容。

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