Попытка развернуть мой сайт, и маршруты API не работают (создайте приложение реакции, express, прокси) - PullRequest
0 голосов
/ 28 марта 2020

Мое приложение работает нормально, когда я использую localhost: 3000, мои маршруты API проксируются через localhost: 8080. После того, как я развернул и попытался посетить / news (это где мой api бьется), он выдает мне следующее сообщение об ошибке: apiFuncs. js: 10 Uncaught (в обещании) TypeError: e.data.map не является функцией.

это мой конфиг сервера

const express = require("express");
const morgan = require("morgan");
const path = require("path");
const app = express();
const port = process.env.PORT || 8080;

require("dotenv").config();

// logging middleware
app.use(morgan());

// body parsing
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// serves static files - react
if (process.env.NODE_ENV === "production") {
  app.use(express.static(path.join(__dirname, "../build")));
}

// redirection /api
app.use("/api", require("./api"));

app.get("*", (req, res) => {
  res.sendFile(path.join(__dirname, "../build", "index.html"));
});

function notFound(req, res, next) {
  res.status(404);
  const error = new Error("Not Found");
  next(error);
}

function errorHandler(error, req, res, next) {
  res.status(res.statusCode || 500);
  res.json({
    message: error.message
  });
}

app.use(notFound);
app.use(errorHandler);

app.listen(port, () => {
  console.log("Listening on port ", port);
});

module.exports = app;

это мой / api

const router = require("express").Router();
const fetch = require("node-fetch");

const baseUrl = "https://newsapi.org/v2/top-headlines?";

router.get("/topHeadlines/:country/:category", (req, res, next) => {
  let endPoint = `${baseUrl}apiKey=${process.env.NEWS_API_KEY}&q=coronavirus&pageSize=100`;
  const { country, category } = req.params;
  endPoint += `&country=${country}&category=${category}`;
  try {
    return fetch(endPoint)
      .then(response => response.json())
      .then(({ articles }) => res.json(articles));
  } catch (error) {
    next(error);
  }
});

router.get("/topHeadlines/:filter", (req, res, next) => {
  let endPoint = `${baseUrl}apiKey=${process.env.NEWS_API_KEY}&q=coronavirus&pageSize=100`;
  if (req.params.filter.length === 2) endPoint += `&country=${req.params.filter}`;
  else endPoint += `&category=${req.params.filter}`;
  return fetch(endPoint)
    .then(response => response.json())
    .then(({ articles }) => res.json(articles));
});

router.get("/topHeadlines", (req, res) => {
  let endPoint = `${baseUrl}apiKey=${process.env.NEWS_API_KEY}&q=coronavirus&pageSize=100`;
  return fetch(endPoint)
    .then(response => response.json())
    .then(({ articles }) => res.json(articles));
});

module.exports = router;

это функция, которую я вызываю во внешнем интерфейсе, которая ударить по маршруту. сообщение об ошибке находится в .then (({data}))

export const getTopHeadlines = async (country, category) => {
  let baseRoute = `api/topHeadlines`;
  if (country) baseRoute += `/${country}`;
  if (category) baseRoute += `/${category}`;
  return await axios
    .get(baseRoute)
    .then(({ data }) => data.map(article => selectFields(article)))
    .then(articles => filterArticles(articles));
};

Я попытался консоль регистрации ответа и получил

{data: "", status: 200, statusText: "OK", headers: {…}, config: {…}, …}
data: ""
status: 200
statusText: "OK"
headers: {connection: "keep-alive", content-length: "0", content-type: "application/json; charset=utf-8", date: "Sat, 28 Mar 2020 19:15:11 GMT", server: "Cowboy", …}
config: {url: "api/topHeadlines", method: "get", headers: {…}, transformRequest: Array(1), transformResponse: Array(1), …}
request: XMLHttpRequest {readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, onreadystatechange: ƒ, …}
__proto__: Object

это мой пакет. json

{
  "name": "calamity-monitor",
  "version": "1.0.0",
  "main": "src/index.js",
  "private": true,
  "dependencies": {
    "@google-cloud/storage": "^4.6.0",
    "@material-ui/core": "^4.9.7",
    "@material-ui/icons": "^4.9.1",
    "@material-ui/styles": "^4.9.6",
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.5.0",
    "@testing-library/user-event": "^7.2.1",
    "axios": "^0.19.2",
    "calcite-react": "^0.49.0",
    "child-process-promise": "^2.2.1",
    "cors": "^2.8.5",
    "dotenv": "^8.2.0",
    "esri-loader": "^2.13.0",
    "express": "^4.17.1",
    "firebase": "^7.11.0",
    "firebase-functions": "^3.5.0",
    "firebase-tools": "^7.15.1",
    "framer-motion": "^1.10.2",
    "local-storage-fallback": "^4.1.1",
    "material-ui": "^0.20.2",
    "morgan": "^1.10.0",
    "newsapi": "^2.4.0",
    "node-fetch": "^2.6.0",
    "nodemon": "^2.0.2",
    "os": "^0.1.1",
    "react": "^16.13.0",
    "react-dom": "^16.13.0",
    "react-infinite-scroll-component": "^5.0.4",
    "react-router-dom": "^5.1.2",
    "react-scripts": "3.4.0",
    "react-slick": "^0.25.2",
    "reselect": "^4.0.0",
    "styled-components": "^5.0.1",
    "styled-theming": "^2.2.0",
    "use-dark-mode": "^2.3.1"
  },
  "scripts": {
    "start": "react-scripts start & nodemon server/server.js",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "proxy": "http://localhost:8080",
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "node-sass": "^4.13.1",
    "sass": "^1.26.3",
    "typescript": "^3.8.3"
  }
}

веб-сайт: https://calamity-monitor.herokuapp.com/news

...