Готовится приложение React для развертывания Heroku; Перестали работать вызовы API; Получение необработанного (в обещании) TypeError; свойство 'имя' не определено;

У меня есть простое приложение SPA, которое я пытался подготовить для развертывания в Heroku (добавление server.js, webpack.config и настройка package.json с помощью сценариев "start" и "postinstall").

Теперь я получаю неопределенную ошибку переменной в обещании, возвращаемом в вызове API для извлечения данных. Приложение использует избыточное обещание, и у рассматриваемой функции обещание разрешено, но ошибка остается.

После некоторого исследования я сузил проблему, возможно, до экспресс-вызова app.get в server.js. Поскольку это SPA, код, использующий ' ', по-видимому, принимает все вызовы API и возвращает или отправляет index.html, основываясь на моих журналах консоли, тем самым вызывая неопределенную ошибку. Я попытался изменить ' ' на '/', но без изменений - запрос не был обработан, что заканчивается ошибкой "404 Not Found".

На консоли newtwork браузера я вижу, что "URL запроса" стал URL приложения Heroku, добавляемым строкой вызова API. В разработке "URL запроса" является localhost:8080. Похоже, что экспресс-сервер принимает все вызовы API и возвращает index.js или любой другой файл, который я "повторно отправляю".

Как я могу это исправить, чтобы вызовы API фактически перенаправляли на внешний API?

Мой код в действии создателя:

import axios from 'axios';

const API_KEY = 'redacted';
const ROOT_URL = `api.openweathermap.org/data/2.5/forecast?appid=${API_KEY}`;
export const FETCH_WEATHER = 'FETCH_WEATHER';

export function fetchWeather(city) {
  const url = `${ROOT_URL}&q=${city},us`;
  console.log(url);
  const request = axios.get(url);
  return {
    type: FETCH_WEATHER,
    payload: request
  };
}

Я мой server.js:

const express = require('express');
const path = require('path');

const port = process.env.PORT || 8080;
const app = express();

app.use(express.static(__dirname));

app.get('*', (req, res) => {
  res.sendFile(path.resolve(__dirname, 'index.html'));
});

app.listen(port);
console.log('Server started');

Вот сообщение об ошибке в консоли:

Uncaught (in promise) TypeError: Cannot read property 'name' of undefined
    at value (bundle.js:19)
    at Array.map (<anonymous>)
    at t.value (bundle.js:19)
    at c._renderValidatedComponentWithoutOwnerOrContext (bundle.js:26)
    at c._renderValidatedComponent (bundle.js:26)
    at c._updateRenderedComponent (bundle.js:26)
    at c._performComponentUpdate (bundle.js:26)
    at c.updateComponent (bundle.js:26)
    at c.receiveComponent (bundle.js:26)
    at Object.receiveComponent (bundle.js:1)
value @ bundle.js:19
value @ bundle.js:19
_renderValidatedComponentWithoutOwnerOrContext @ bundle.js:26
_renderValidatedComponent @ bundle.js:26
_updateRenderedComponent @ bundle.js:26
_performComponentUpdate @ bundle.js:26
updateComponent @ bundle.js:26
receiveComponent @ bundle.js:26
receiveComponent @ bundle.js:1
_updateRenderedComponent @ bundle.js:26
_performComponentUpdate @ bundle.js:26
updateComponent @ bundle.js:26
performUpdateIfNecessary @ bundle.js:26
performUpdateIfNecessary @ bundle.js:1
u @ bundle.js:1
perform @ bundle.js:1
perform @ bundle.js:1
perform @ bundle.js:1
x @ bundle.js:1
closeAll @ bundle.js:1
perform @ bundle.js:1
batchedUpdates @ bundle.js:18
s @ bundle.js:1
r @ bundle.js:2
enqueueSetState @ bundle.js:2
r.setState @ bundle.js:18
n.handleChange @ bundle.js:25
c @ bundle.js:18
(anonymous) @ bundle.js:27
dispatch @ bundle.js:27
(anonymous) @ bundle.js:27
Promise.then (async)
(anonymous) @ bundle.js:27
(anonymous) @ bundle.js:27
value @ bundle.js:19
r @ bundle.js:18
a @ bundle.js:26
u @ bundle.js:26
p @ bundle.js:1
d @ bundle.js:1
n @ bundle.js:18
processEventQueue @ bundle.js:1
r @ bundle.js:26
handleTopLevel @ bundle.js:26
a @ bundle.js:26
i @ bundle.js:26
perform @ bundle.js:1
batchedUpdates @ bundle.js:18
i @ bundle.js:1
dispatchEvent @ bundle.js:26

Вот мой package.json:

   {
  "name": "redux-simple-starter",
  "version": "1.0.0",
  "engines": {
    "node": "9.3.0"
  },
  "description": "Simple starter package for Redux with React and Babel support",
  "main": "index.js",
  "repository": "git@github.com:StephenGrider/ReduxSimpleStarter.git",
  "scripts": {
    "dev": "node ./node_modules/webpack-dev-server/bin/webpack-dev-server.js",
    "start": "node server.js",
    "postinstall": "NODE_ENV=production webpack -p",
    "test": "mocha --compilers js:babel-core/register --require ./test/test_helper.js --recursive ./test",
    "test:watch": "npm run test -- --watch"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {},
  "dependencies": {
    "axios": "^0.18.0",
    "babel-core": "^6.2.1",
    "babel-loader": "^6.2.0",
    "babel-preset-es2015": "^6.1.18",
    "babel-preset-react": "^6.1.18",
    "babel-preset-stage-1": "^6.1.18",
    "chai": "^3.5.0",
    "chai-jquery": "^2.0.0",
    "express": "^4.16.2",
    "jquery": "^2.2.1",
    "jsdom": "^8.1.0",
    "lodash": "^3.10.1",
    "mocha": "^2.4.5",
    "react": "^0.14.3",
    "react-addons-test-utils": "^0.14.7",
    "react-dom": "^0.14.3",
    "react-redux": "4.3.0",
    "react-router": "^2.0.1",
    "react-sparklines": "1.4.2",
    "redux": "^3.0.4",
    "redux-actions": "^2.3.0",
    "redux-promise": "^0.5.3",
    "redux-thunk": "^2.2.0",
    "webpack": "^1.12.9",
    "webpack-dev-server": "^1.14.0"
  }
}

Вот мой webpack.config.js:

var webpack = require('webpack');

module.exports = {
  entry: [
    './src/index.js'
  ],
  output: {
    path: __dirname,
    publicPath: '/',
    filename: 'bundle.js'
  },
  module: {
    loaders: [{
      exclude: /node_modules/,
      loader: 'babel',
      query: {
        presets: ['react', 'es2015', 'stage-1']
      }
    }]
  },
  resolve: {
    extensions: ['', '.js', '.jsx']
  },
  devServer: {
    historyApiFallback: true,
    contentBase: './'
  },
  plugins: [
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV)
    }),
  ]
};

0 ответов

Другие вопросы по тегам