首页 > 解决方案 > Which base url should I use when I perform GET request with Axios in Heroku with React.js

问题描述

I'm working with a MERN stack app. This app works perfectly when I run it locally , but I'm not sure why my Axios get request doesn't work in my React components when I run my app in Heroku.

In this bit of code, the Axios get call returns me a plain html object.

import { useState, useEffect} from "react";
const axios = require('axios').default;

function MyReactComponent() {

    const [data, setData] = useState([]);

    useEffect(() => {

        axios.get("/api/standings").then(response => {
            const myData = response.data

            console.log(myData);

            //logs a plain html object working in heroku
        });

    }, []);

    return (
        <div>
            <h1>Hello, this is an example</h1>
        </div>
    )
}

export default MyReactComponent;

When I do it with promises it logs undefined:

import { useState, useEffect } from "react";
const axios = require('axios').default;

function MyReactComponent() {

    useEffect(() => {

        const [data, setData] = useState([]);

        return new Promise((resolve, reject) => {
            axios
                .get("/api/standings")
                .then(res => {
                    resolve(res.data)
                    console.log(resolve(res.data))

                    //logs undefined working in heroku
                }, err => reject(err));
        });
    });

    return (
        <div>
            <h1>Hello, this is an example</h1>
        </div>
    )
}

export default MyReactComponent;

I've to point out that working locally I must use Proxy in the "package.json" in my front-end folder in order to make Axios perform the request without getting a 404 error:

"proxy": "http://localhost:4000"

I know that if I put "/ANYTHINGELSE" when performing Axios call, the base URL is "https://appname.herokuapp.com". So What should I do?

标签: javascriptreactjsherokumongooseaxios

解决方案


我已经解决了,不是axios问题,更不是前端问题。

在我的后端,定义我的服务器的 index.js 文件是这样的:


require("dotenv").config();
const express = require("express");
const app = express();
var cors = require('cors')
const path = require('path');
const bodyParser = require("body-parser");
const mongoose = require("mongoose");


//SETTINGS
app.use(cors());
app.set("port", process.env.PORT || 4000);

.
. //ETC
.

//THEN, Defining what front-end should show if heroku is on production

if (process.env.NODE_ENV === 'production') {
    app.use(express.static(path.join(__dirname, '../../frontend/build')));
    app.get('*', (req, res) => {
        res.sendFile(path.join(__dirname, '../../frontend/build/index.html'));
    })

//And then my server routes...

//ROUTES
app.use("/api/standings", require("./routes/standings"));
app.use("/api/races", require("./routes/races"));
app.use("/api/f1datas", require("./routes/f1datas"));


.
.//More code
.

最后一部分应该交换

//ROUTES
app.use("/api/standings", require("./routes/standings"));
app.use("/api/races", require("./routes/races"));
app.use("/api/f1datas", require("./routes/f1datas"));

//THEN

if (process.env.NODE_ENV === 'production') {
    app.use(express.static(path.join(__dirname, '../../frontend/build')));
    app.get('*', (req, res) => {
        res.sendFile(path.join(__dirname, '../../frontend/build/index.html'));
    })

推荐阅读