我有一个应用,该应用使用express作为我的后端向API发出get请求。这在localhost上很好用,我可以看到正在显示的数据,但是当我将站点部署到Netlify时,它总是返回404:
https://weatherwiz.netlify.com/api/darksky?latitude=-34.5823529&longitude=-58.468295899999994
这是我的后端代码:
const express = require('express');
const bodyParser = require('body-parser');
require('es6-promise').polyfill();
require('isomorphic-fetch');
const http = require('http');
const dotenv = require('dotenv');
const app = express();
const server = http.createServer(app);
dotenv.config();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
const key = process.env.REACT_APP_API_KEY;
const url = `https://api.darksky.net/forecast/${key}/`;
app.get('/api/darksky', (req, res) => {
try {
const fullURL = `${url}${req.query.latitude},${req.query.longitude}?units=si`;
fetch(fullURL)
.then(response => {
return response.json();
})
.then(response => {
res.status(200).json(response);
});
} catch(error) {
res.status(500).json({'message': 'Dark Sky API error', 'error' : error});
}
});
server.listen('3001');
console.log('Server listening on port 3001');
这是我在React应用程序上从App.js调用它的方式:
queryDarkSky = (latitude, longitude, time = false) => {
const url = time ? `/api/darksky?latitude=${latitude}&longitude=${longitude},${time}` : `/api/darksky?latitude=${latitude}&longitude=${longitude}`; 2
darkSky(url, this.onSuccess, this.onError);
}
这是发出请求的帮助函数:
export function darkSky(url, onRequestSuccess, onRequestFailure) {
fetch(url)
.then(res => {
if (!res.ok) {
console.log('error', res);
}
return res;
}).catch(error => {
throw error;
})
.then(res => {
return res.json()
})
.then((json) => {
onRequestSuccess(json);
}).catch((error) => {
const response = error.response;
if (response === undefined) {
onRequestFailure(error);
} else {
error.status = response.status;
error.statusText = response.statusText;
response.text().then(text => {
try {
const json = JSON.parse(text);
error.message = json.message;
} catch (ex) {
error.message = text;
}
onRequestFailure(error);
});
}
});
}
任何帮助表示感谢,谢谢!