我有一个express.js服务器,该服务器发出HTTP GET请求以检索天气数据。在我的JavaScript中,我获得了经度和纬度变量。我需要使用fetch将这些变量发送到我的express.js服务器。我该怎么办?
我尝试将查询参数作为请求对象的主体发送,但是我了解到GET请求无法做到这一点。
Express服务器代码:
app.get("/data", (req, res) => {
url = `http://api.openweathermap.org/data/2.5/uvi?appid=${API}&lat=${latitude}&lon=${longitude}`;
axios
.get(url)
.then(response => {
res.send(response.data);
})
.catch(error => {
console.log(errorx);
});
});
如何从JavaScript获取纬度和经度变量?
我希望快递服务器具有必需的变量并执行GET请求。
答案 0 :(得分:0)
我将与您分享一个我之前做过的例子。为我工作。
/server.js
var http = require('http');
var fs = require('fs');
var express = require('express');
var app = express();
var path = require('path');
app.use(function (req, res, next) {
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8080');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
res.setHeader('Access-Control-Allow-Credentials', true);
next();
});
app.use('/app', express.static(__dirname + '/app'));
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname + '/app/index.html'));//my app page , may be different for you
});
var routes = require('./scripts/routes');
routes(app);
app.listen(8080);
console.log('-> Port : 8080');
/scripts/routes.js
'use strict';
module.exports = function (app) {
var todoList = require('../scripts/controller');
app.route('/company/:companyId')
.get(todoList.getInfo)
app.route('/product-add/:name/:meter')
.get(todoList.addPro);
};
/scripts/controller.js
'use strict';
var sql = require("mssql");//I used mssql. may be different for you
var request = new sql.Request();
exports.getInfo = function (req, res) {
var comId = req.params.companyId
request.query('select * from company where id='+comId , function (err, recordset) {
if (err) console.log(err)
res.json(recordset);
});
};
exports.addPro = function (req, res) {
// req.params.name
// req.params.meter
};
答案 1 :(得分:0)
查询字符串参数是请求URL的一部分。
在执行GET请求时,假设端点为http://localhost:3000/data?lat=0&long=0,请尝试以下操作传递纬度和经度
app.get("/data", (req, res) => {
// Add this to retrieve query string values
let latitude = req.query.lat;
let longitude = req.query.long;
// Rest of your code
});