[英]how can i receive the body of an axios post request with express nodejs?
[英]How can I retrieve the value from a http request? NODEJS + EXPRESS
我需要檢索請求發回給我的坐標。
請求是正確的,在body
body 上我可以訪問 lat 和 lon。 問題是,請求在另一個名為latlongfunc
函數中。 如何在請求調用之外訪問正文?
我已經嘗試過:在調用之前創建一個variable
,然后在調用內部修改它,最后在函數 latlongfunc 的末尾返回它。 它不起作用...
重要提示:請求有效,問題在於如何訪問請求之外的正文。
const request = require('request') console.log("Here.") var latlongfunc = async (fullAddress) => { var options = { url: `https://nominatim.openstreetmap.org/search/${fullAddress}`, json: true, // JSON strigifies the body automatically headers: { 'User-Agent': 'request' } }; request(options, (err, res, body) => { if(body.length > 0){ // A body was received var coordinate = { lat: body[0].lat, lon: body[0].lon } return coordinate }else{ console.log("Something wrong happened") } }) } module.exports = { latlongfunc };
只需將您的代碼包裝在一個可以解決您需要的坐標的承諾中。
const request = require('request')
console.log("Here.")
var latlongfunc = (fullAddress) => {
var options = {
url: `https://nominatim.openstreetmap.org/search/${fullAddress}`,
json: true, // JSON strigifies the body automatically
headers: {
'User-Agent': 'request'
}
};
return new Promise((resolve, reject) => {
request(options, (err, res, body) => {
if(err) {
return reject(err);
}
if(body.length > 0){
// A body was received
var coordinate = {
lat: body[0].lat,
lon: body[0].lon
}
resolve(coordinate);
}else{
console.log("Something wrong happened")
}
})
})
}
module.exports = {
latlongfunc
};
const latlongfunc = require("latlongfunc");
latlongfunc.then(coordinate => console.log(coordinate));
我的建議是使用request-promise
包,它用Promise
包裝request
const rp = require('request-promise')
const request = require('request')
var latlongfunc = async (fullAddress) => {
let coordinate
try {
var options = {
url: `https://nominatim.openstreetmap.org/search/${fullAddress}`,
json: true, // JSON strigifies the body automatically
headers: {
'User-Agent': 'request'
}
};
const body = await rp(options)
var coordinate = {
lat: body[0].lat,
lon: body[0].lon
} catch (e) {
// handle error or throw
console.log("Something wrong happened")
}
return coordinate
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.