2016-02-12 317 views
0

我遇到了一個我認爲可能的問題。使用Express.js在服務器上發送POST請求

我想要兩條快線,一條GET路線/post-data和一條POST路線/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請求。

這可能嗎?

我知道你可以使用類似request這樣的庫來向端點發送HTTP POST請求,但是我正在討論通過POST請求實際發送用戶到頁面。

+0

但是......爲什麼? – adeneo

+0

@adeneo我有一個來自第三方的請求,正在打我的服務器。我希望能夠嘲笑我的服務器上的POST請求。 – ThomasReggi

+0

請參閱http://stackoverflow.com/questions/46582/response-redirect-with-post-instead-of-get和https://en.wikipedia.org/wiki/Post/Redirect/Get。我的理解是,客戶端只能發出請求方法,例如'GET /index.php HTTP/1.1;主機:www.example.org',並且來自服務器的重定向頭在客戶端之後使用相同的方法,例如, 'HTTP/1.1 301永久移動;位置:http://www.example.org/index.asp。從您的評論中,這聽起來像你想作爲代理,在這種情況下*你*將執行POST,然後將響應發送給客戶端。 –

回答

0

這感覺很笨,但它可能是唯一的方式?

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)) 
0

以編程方式將客戶端請求方法從GET更改爲POST的唯一方法是創建一個包含隱含元素的表單,其中包含method="post"action="/post-receive",然後使用客戶端JavaScript自動提交表單。

響應GET請求的任何HTTP重定向也將是GET。

0

您可以使用request-promise將數據發佈到url。所以,啓動這個功能,你可以得到的數據在API網址

const request = require('request'); 
const rp = require('request-promise'); 

let req = { 
     "param1" : "data1", 
     "param1" : "data2"  
    }  
    rp({ 
     method: 'POST', 
     uri: 'http://localhost:3000/post-data/', 
     body: req, 
     json: true // Automatically stringifies the body to JSON 
     }).then(function (parsedBody) { 
       console.dir(parsedBody); 
       return parsedBody; 
       // POST succeeded... 
      }) 
      .catch(function (err) { 
       console.log(err+'failed to post data.'); 
       return err+'failed to post data.'; 
       // POST failed... 
     }); 

道歉如果我把你的問題錯了。