正如我在标题中提到的,我有一个API,可为我提供有关国家的详细信息。我已经创建了一个处理API请求的快速服务器。问题是它没有发出请求,但是从浏览器URL请求时,相同的URL返回JSON。另一方面,我尝试了另一个API,该API返回了我一个答案。所以我对这种情况感到困惑。我需要该API的响应。 这是我的服务器代码`
const express = require('express');
const request = require('request');
const bodyParser = require('body-parser');
const port = process.env.PORT || 3000;
const app = express();
app.use(express.static('public'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
let country = '';
request({
url: `https:restcountries.eu/rest/v2/name/${country}?fullText=true`,
json: true
}, (error, response, body) => {
console.log('ddfd');
if (!error && response.statusCode === 200) {
console.log(body, 'body');
}
});
app.get('/countries', (req, res) => {
country = req.query.name;
console.log(country, 'country');
});
app.listen(port, () => {
console.log(`Server is up on port ${port}`);
});
答案 0 :(得分:0)
尝试一下。为什么不在api中调用请求?
app.get('/countries', (req, res) => {
country = req.query.name;
console.log(country, 'country');
request({
url: `https:restcountries.eu/rest/v2/name/${country}?fullText=true`,
json: true
}, (error, response, body) => {
if (!error && response.statusCode === 200) {
console.log(body, 'body');
res.send(body);
}
});
});