简体   繁体   English

Express.js发送数据以通过发布获取请求

[英]Express.js send data to get request through post

I've a form with express.js: 我有一个express.js的表单:

app.get("/", function (req, res) {
  if (req.body.something) {
    // Do something
  }
  res.send(myform);
});
app.post("/", function (req, res) {
  if (req.body.foobar == false) {
     // I need to set req.body.something and make it visible to "get"
  }}
});

My form: 我的表格:

<form method="post" action="/">
  <input type="checkbox" name="foobar">
  <input type="submit" value="submit">
</form>

I need a way to send data with "post" method and make it visible by the "get" method. 我需要一种使用“ post”方法发送数据并通过“ get”方法使其可见的方法。 How can I do? 我能怎么做?

There are probably a number of ways to do this. 可能有多种方法可以做到这一点。 One option is to store the POST values in a session. 一种选择是将POST值存储在会话中。

app.post("/", function (req, res) {
  if (req.body.foobar == false) {
    //Store foobar from body of POST into the session
    req.session.foobar = req.body.foobar;
    // Other stuff...
  }}
});

app.get("/", function (req, res) {
  if (req.body.something) {
  // Do something
     doStuff(req.session.foobar) // Here we use the foobar set in POST
     //DO MORE STUFF
  }
  res.send(myform);
});

To use this before add something similar to below enable sessions. 要使用此功能,请先添加类似于以下启用会话的内容。

app.use(session({secret: 'fabecefd-387c-4dc9-a525-25d1fab00330'}));

More Documentation on https://github.com/expressjs/session 有关https://github.com/expressjs/session的更多文档

Additional note: Please validate your input, handle error conditions, and structure your code your own way. 附加说明:请验证您的输入,处理错误情况,并以自己的方式构建代码。 The above was a very basic example on how to use sessions. 上面是关于如何使用会话的非常基本的示例。

You can send data with the GET method using jQuery : 您可以使用jQuery使用GET方法发送数据:

$.ajax({
  type: 'GET',
  data: 'Your body content here'
});

Or using curl from a terminal : 或者从终端使用curl:

curl -XGET -d "Your body content" http://localhost:3000/
app.get("/", function (req, res) {
  if (req.body.something) {
    app.get('setKey');
  }
 res.json(req.body);
});

app.post("/", function (req, res) {
 if (req.body.foobar == false) {
   app.set('setKey','setValue');
 }}
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM