簡體   English   中英

如何將 POST 請求發送到另一個 node.js 服務器

[英]How to send POST request to another node.js server

我做了兩台服務器

var express = require('express'); var querystring = require('querystring'); var http = require('http'); var app = express(); app.get('/', function (req, res) { var data = querystring.stringify({ username: 'myname', password: 'pass' }); var options = { host: 'localhost', port: 8081, path: '/demo', method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Content-Length': Buffer.byteLength(data) } }; var httpreq = http.request(options, function (response) { response.setEncoding('utf8'); response.on('data', function (chunk) { console.log("body: " + chunk); }); response.on('end', function() { res.send('ok'); }) }); httpreq.write(data); httpreq.end(); }); app.listen(8090, function(){ console.log('Server start on 8090'); });

第二個是

var express = require('express'); var app = express(); app.post('/demo', function(req, res){ console.log('Body: ', req.body); }); app.listen(8081, function(){ console.log('Server Start on 8081'); });

我想將數據從 localhost:8090 發送到 localhost:8081。

但是在第二個服務器端,當我嘗試打印 req.body 它告訴我

Server Start on 8081 Body: undefined

幫助我找到解決方案。 如果你有更好的代碼,那么這對我有好處。

提前感謝您的幫助。

您的正文在您的快速服務器中未定義的原因是因為您沒有使用body-parser中間件。 Express 無法像您在請求中指定的那樣解析 Content-Type x-www-form-urlencoded的請求正文。 同樣在您的請求中,您不是通過請求正文發送數據,而是在查詢 string 中發送數據,因此您的 Express Route 需要檢查查詢 string 而不是正文。

你需要讓你的 Express 看起來像這樣:

 const express = require('express'); const bodyParser = require('body-parser'); const app = express(); const port = process.env.PORT || 1337; app.use(bodyParser.urlencoded({ extended: true }); // Parse x-www-form-urlencoded app.post('/demo', (req, res) => { console.log(`Query String: ${req.query}`); console.log(`Body: ${req.body}`); }); app.listen(port, () => { console.log(`Listening on ${port}`); });

你可以這樣請求

require('request').post( "localhost:8081/demo", {form: { username: "name", password: "any" } }, function(error, response, body){ console.log(body); } );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM