简体   繁体   English

Heroku 应用程序在部署到 heroku 时获得 503 响应

[英]Heroku app getting 503 reponse when deployed to heroku

I have here an app that displays the location of the ISS on a map, and a user can send a message to the ISS which puts an icon where the ISS was when the message was sent.我在这里有一个应用程序,它在地图上显示 ISS 的位置,用户可以向 ISS 发送消息,该消息在发送消息时在 ISS 所在的位置放置一个图标。

It works wonderfully both when I start up the server and client locally and when I use the server to send the index.html page, but as soon as I deploy to Heroku, the requests to the server are failing and I cannot get the ISS location or add a message.当我在本地启动服务器和客户端以及使用服务器发送 index.html 页面时,它都能很好地工作,但是一旦我部署到 Heroku,对服务器的请求就会失败,我无法获得 ISS 位置或添加消息。

Here is my index.js file这是我的 index.js 文件

const express = require("express");
const app = express();
const path = require("path");
const cors = require("cors");
const coords = require("./schema");
const axios = require("axios");
var moment = require("moment");
moment().format();

app.use(express.json());

app.use(cors("*"));

app.post("/message", (req, res) => {
  axios
    .get(
      `https://nominatim.openstreetmap.org/reverse?lat=${req.body.lat}&lon=${req.body.long}&format=json`
    )
    .then(({ data }) => {
      var testCoords = new coords({
        lat: req.body.lat,
        long: req.body.long,
        text: req.body.text,
        date: Date.now(),
        location: data.error ? "the ocean" : data.display_name
      });

      testCoords.save(err => {
        if (err) {
          console.log(err);
        } else {
          coords.find({}, (err, docs) => {
            res.status(200).send(docs);
          });
        }
      });
    });
});

app.get("/message", (req, res) => {
  coords.find({}, (err, docs) => {
    res.status(200).send(docs);
  });
});

app.use(express.static(`${__dirname}/../build`));

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

app.listen(process.env.PORT || 3000, () => {
  console.log("Server started");
});


and my App.js client和我的 App.js 客户端

import React, { Component } from "react";
import { Map, Marker, TileLayer, Popup } from "react-leaflet";
import axios from "axios";
import L from "leaflet";
import Form from "./Form";
import Moment from 'moment';
export default class App extends Component {
  constructor() {
    super();
    this.state = {
      lat: "",
      long: "",
      zoom: 10,
      messages: [],
      showForm: true
    };
  }

  componentDidMount = () => {
    axios.get("/message").then(res => {
      this.setState({
        messages: res.data
      });
      setInterval(this.getIss, 2500);
    });
  };

  postMessage = message => {
    axios
      .post("/message", {
        text: message,
        lat: this.state.lat,
        long: this.state.long
      })
      .then(res => {
        this.setState({
          messages: res.data,
          showForm: false
        });
      });
  };

  getIss = () => {
    axios.get("https://api.wheretheiss.at/v1/satellites/25544").then(res => {
      this.setState({
        lat: res.data.latitude,
        long: res.data.longitude
      });
    });
  };

  formatDate = date => { 
    return Moment(date)
      ._d.toString()
      .split(" ")
      .splice(0, 4)
      .join(" ");
  }
  render() {
    const myIcon = L.icon({
      iconUrl: require("./assets/ISS-sm.png"),
      iconSize: [64, 64],
      iconAnchor: [32, 64],
      popupAnchor: null,
      shadowUrl: null,
      shadowSize: null,
      shadowAnchor: null
    });

    const messages = this.state.messages.map(message => {
      return (
        <Marker position={[message.lat, message.long]}>
          <Popup>
            <div>
              <h1>{message.text}</h1>
              <p>{`${this.formatDate(message.date)} over ${message.location}`}</p>
            </div>
          </Popup>
        </Marker>
      );
    });
    return (
        <div>
          <Form postMessage={this.postMessage} show={this.state.showForm} />
          <Map center={[this.state.lat, this.state.long]} zoom={3}>
            <TileLayer
              url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
              attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
            />
            {messages}
            <Marker
              icon={myIcon}
              position={[this.state.lat, this.state.long]}
            />
          </Map>
        </div>
    );
  }
}

I get a 503 error.我收到 503 错误。

I have tried sending a GET to https://myherokuapp.com/messages , but that also does not work.我曾尝试将 GET 发送到https://myherokuapp.com/messages ,但这也不起作用。 and I do not know how to get this thing to run properly.我不知道如何让这个东西正常运行。

Any help is appreciated.任何帮助表示赞赏。

I'm not really sure without knowing what's in "./schema" , since that seems to be some sort of mapping/lat-long schema.在不知道"./schema"内容的情况下,我不太确定,因为这似乎是某种映射/ "./schema"模式。 Of course, when I ran your code, I got a Error: Cannot find module './schema' error, which... makes sense, since I don't have that file.当然,当我运行你的代码时,我得到了一个Error: Cannot find module './schema'错误,这是有道理的,因为我没有那个文件。

Keeping in mind that an error in your front-end code should not (usually!) return a 5xx error, your best bet in this case is to view the Heroku logs and see what's happening on the back-end.请记住,前端代码中的错误不应(通常!)返回 5xx 错误,在这种情况下,最好的办法是查看 Heroku 日志并查看后端发生了什么。

To do this:去做这个:

  1. Go to your Heroku dashboard for the app in question.转到相关应用程序的 Heroku 仪表板。
  2. In the top-right, click the "More" button, and then click "Restart all dynos. This isn't strictly necessary, but it'll help you by allowing you to pinpoint exactly when the problem(s) occurred.在右上角,单击“更多”按钮,然后单击“重新启动所有 dynos。这不是绝对必要的,但它可以帮助您准确定位问题发生的时间。
  3. In your console, assuming you have the heroku CLI installed (if not, do that!) do heroku logs --app myherokuapp --tail , where myherokuapp is of course the name of your app.在您的控制台中,假设您安装了 heroku CLI(如果没有,请安装!)执行heroku logs --app myherokuapp --tail ,其中myherokuapp当然是您的应用程序的名称。
  4. Try going to your (live) website, and take a look at the logs.尝试访问您的(实时)网站,并查看日志。 Do they show anything?他们有什么表现吗?

In general, an HTTP 503 means "service unavailable", meaning that whatever server it is you're trying to reach is not responding, or otherwise, well, unavailable.通常,HTTP 503 表示“服务不可用”,这意味着您尝试访问的任何服务器都没有响应,或者不可用。

Some preliminary research shows that in a lot of cases, 503's can be the result of someone not having an appropriate dependency saved in their package.json file, so check that first: Try copying your project ( except the node_modules folder!) to another folder, running npm install , and then npm start (or node index.js or whatever).一些初步研究表明,在很多情况下,503 可能是某人没有在他们的package.json文件中保存适当的依赖项的结果,因此首先检查:尝试将您的项目(除了node_modules文件夹!)复制到另一个文件夹,运行npm install ,然后npm start (或node index.js或其他)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM