2017-02-10 106 views
0

我想從一個nodeJS服務器向另一個發送HTTPS POST。我有一些JSON數據,我想用這個請求發送(由html表單填充)。nodeJS - 發出HTTPS請求,發送JSON數據

我該怎麼做?我知道https.request(),但似乎沒有選擇將JSON作爲查詢的一部分。從我的研究看來,HTTP請求似乎是可能的,但不是HTTPS請求。我該如何解決這個問題?

const pug = require('pug'); 
var cloudinary = require('cloudinary'); 
var express = require('express'); 
var multer = require('multer'); 
var upload = multer({ dest: 'uploads/' }); 
var request = require('request'); 
var bodyParser = require('body-parser'); 

var options = { 
hostname: 'ec2-54-202-139-197.us-west-2.compute.amazonaws.com', 
port: 443, 
path: '/', 
method: 'GET' 
}; 

var app = express(); 
var parser = bodyParser.raw(); 
app.use(parser); 

app.set('view engine', 'pug'); 

app.get('/', upload.single('avatar'), function(req, res) { 
return res.render('index.pug'); 
}); 

app.get('/makeRequest*', function(req, res) { 
query = req['query']; 
/* 
Here, I would like to send the contents of the query variable as JSON to the server specified in options. 
*/ 
}); 

回答

2

您可以通過與本地HTTPS節點模塊POST HTTP請求發送JSON數據,stated in the documentation

從http.request所有選項()是有效的。

所以,服用http.request()例如,你可以做到以下幾點:

var postData = querystring.stringify({ 
    'msg' : 'Hello World!' 
}); 

var options = { 
    hostname: 'www.google.com', 
    port: 80, 
    path: '/upload', 
    method: 'POST', 
    headers: { 
    'Content-Type': 'application/x-www-form-urlencoded', 
    'Content-Length': Buffer.byteLength(postData) 
} 
}; 

var req = https.request(options, (res) => { 
    console.log(`STATUS: ${res.statusCode}`); 
    console.log(`HEADERS: ${JSON.stringify(res.headers)}`); 
    res.setEncoding('utf8'); 
    res.on('data', (chunk) => { 
    console.log(`BODY: ${chunk}`); 
    }); 
    res.on('end',() => { 
    console.log('No more data in response.'); 
    }); 
}); 

req.on('error', (e) => { 
    console.log(`problem with request: ${e.message}`); 
}); 

// write data to request body 
req.write(postData); 
req.end(); 

您應該編輯postData到你想要的JSON對象

+0

這不起作用,服務器不會收到postData。 –

+0

我試過了,它確實有效,請記住,如果服務器是節點服務器,那麼在處理請求的服務器中,數據將包含在'req.body'中 –

0

我相信下面是你想要的。使用request庫。在代碼中查看我的建議的評論。

... 

var options = { 
    hostname: 'ec2-54-202-139-197.us-west-2.compute.amazonaws.com', 
    port: 443, 
    path: '/', 
    method: 'POST', 
    json: true 
}; 

... 

//making a post request and sending up your query is better then putting it in the query string 
app.post('/makeRequest', function(req, res) { 
    var query = req.body['query']; 

    //NOTE, you cannot use a GET request to send JSON. You'll need to use a POST request. 
    //(you may need to make changes on your other servers) 
    options.body = { payload: query }; 
    request(options, function(err, response, body) { 
    if (err) { 
     //Handle error 
     return; 
    } 

    if (response.statusCode == 200) { 
     console.log('contents received'); 
    } 

    }); 
});