使用Express.js在服务器上发送POST请求 [英] Send a POST request on the server with Express.js

查看:39
本文介绍了使用Express.js在服务器上发送POST请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了我认为可能的事.

I'm running into a small issue with something I thought was possible.

我想要两条快速路线,一条 GET 路线/post-data 和一条 POST 路线/post-receve.

I want to have two express routes, one GET route /post-data and one POST route /post-recieve.

代码看起来像这样:

app.get('/post-data', (req, res, next) => { 
  //set url to '/post-recieve' and set body / headers
})  

app.post('/post-recieve', (req, res, next) => {
  return res.json(res.body)
})

现在,当您访问/post-data 时,应该立即将其重定向到/post-recieve ,除非您在开发人员控制台中查看,否则应该看到该方法因为该文档是 POST ,而不是常规的 GET 请求.

Now, when you visit /post-data you should be instantly redirected to /post-recieve except if you look in the developer console you should see that the method for the document is POST and not a normal GET request.

这可能吗?

我知道您可以使用类似 request 之类的库向端点发出HTTP发布请求,但是我说的是实际上是通过 POST将用户发送到页面的请求.

I know you can use a library like request to make a HTTP post request to an endpoint, but I'm talking about actually sending the user to the page via a POST request.

推荐答案

这感觉很愚蠢,但这可能是唯一的方法?

This feels so dumb, but it might be the only way???

function postProxyMiddleware (url, data) {
  return (req, res, next) => {
    let str = []
    str.push(`<form id="theForm" action="${url}" method="POST">`)
    each(data, (value, key) => {
      str.push(`<input type="text" name="${key}" value="${value}">`)
    })
    str.push(`</form>`)
    str.push(`<script>`)
    str.push(`document.getElementById("theForm").submit()`)
    str.push(`</script>`)
    return res.send(str.join(''))
  }
}

app.get('/mock', postProxyMiddleware('/page', exampleHeaders))

这篇关于使用Express.js在服务器上发送POST请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆