首页 > 解决方案 > Netlify - 仅在产品中提取时返回 404

问题描述

我有一个应用程序,它使用 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);
        });
      }
    });
}

任何帮助表示赞赏,谢谢!

标签: javascriptreactjsexpressnetlify

解决方案


推荐阅读