Create-React-App + Heroku + Api路线= 404错误

之前,我已经能够将React用于heroku应用程序,并且在heroku上没有React的情况下我已经成功进行了api调用,但是我从未能够将两者混为一谈。甚至没有一次。

api路由可在localhost上使用。

我有难以置信的基本代码,每当我尝试访问部署到Heroku的api路由之一时,都会产生404错误。以下是我的server.js文件:

const express = require("express");
const mongoose = require("mongoose");
const PORT = process.env.PORT || 3001;
const path = require("path");
const routes = require("./routes");
const app = express();

let MONGODB_URI = process.env.MONGODB_URI || "mongodb://localhost/database";

app.use(express.urlencoded({extended:false}));
app.use(express.json());
app.use(express.static("public"));

if (process.env.NODE_ENV === "production") {
    app.use(express.static("client/build"));
}

mongoose.connect(MONGODB_URI,{useNewUrlParser: true,useUnifiedTopology: true});
mongoose.connection.on("connected",function() {
    console.log("~ Connected To Database ~");
});

app.use(routes);

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

app.listen(PORT,function() {
    console.log("App listening in on " + PORT);
});

我的api路由是通过文件结构设置的:

  

routes(与server.js位于同一目录中)

     
    

index.js     api.js

  

这里是index.js

const apiRoutes = require("./api.js");
const router = require("express").Router();

router.use("/api",apiRoutes);

module.exports = router;

这是api.js

const router = require("express").Router();

router.get("/users/all",res) {
    console.log("Running! The API Route is Being Called!");

    res.send("Success");
});

module.exports = router;

这里是启动axios调用的Base react组件:

import React,{Component} from "react";
import "./style.css";
import axios from "axios";


class Base extends Component {
    testAxios = async () => {
        axios.get("/api/users/all");   
    }

    render() {
        return (
            <div>
            <p>Helloooo</p>
            <button onClick = {this.testAxios}>Test Axios</button>
            </div>
        )
    }
}

export default Base;

最后,这是相关的package.json文件:

对于客户端文件夹:

{
  "name": "client","version": "0.1.0","private": true,"dependencies": {
    "react": "^16.12.0","react-dom": "^16.12.0","react-router-dom": "^5.1.2","react-scripts": "3.2.0"
  },"scripts": {
    "start": "react-scripts start","build": "react-scripts build","test": "react-scripts test","eject": "react-scripts eject"
  },"eslintConfig": {
    "extends": "react-app"
  },"browserslist": {
    "production": [
      ">0.2%","not dead","not op_mini all"
    ],"development": [
      "last 1 chrome version","last 1 firefox version","last 1 safari version"
    ]
  }
}

对于根文件夹:

{
  "name": "garbage","version": "1.0.0","description": "","main": "server.js","scripts": {
    "test": "echo \"Error: no test specified\" && exit 1","start": "if-env NODE_ENV=production && npm run start:prod || npm run start:dev","start:prod": "node server.js","start:dev": "concurrently \"nodemon --ignore 'client'/*'\" \"npm run client\"","install": "cd client && npm install","client": "cd client && npm run start","build": "cd client && npm run build","heroku-postbuild": "cd client && npm install --only=dev && npm install && npm run build"
  },"devDependencies": {
    "concurrently": "^5.0.0","nodemon": "^1.19.4","http-server": "^0.11.1"
  },"keywords": [],"author": "","license": "ISC","dependencies": {
    "axios": "^0.19.0","concurrently": "^5.0.0","express": "^4.17.1","mongoose": "^5.7.10","node": "^12.11.1","nodemon": "^1.19.3","react": "^16.10.2","react-router-dom": "^5.1.2"
  },"repository": {
    "type": "git","url": "git+https://github.com/garbage/garbage.git"
  }
}

我尝试添加一个static.json文件,但没有成功。如果您有任何想法,请告诉我。

zhy123456789zhy 回答:Create-React-App + Heroku + Api路线= 404错误

我发现了问题的根源。在package.json中,只有一行:

"scripts": { "start": "node server.js","start:original": "if-env NODE_ENV=production && npm run start:prod || npm run start:dev" }

顾名思义,"start:original"行是原始的启动函数。我不再依赖"if-env NODE...",而是简单地将其替换为"node server.js"。当我要开发并想同时启动服务器时,我现在只使用node run start:dev

从那时起,我所有的React应用程序都已成功使用api路由。

本文链接:https://www.f2er.com/3055426.html

大家都在问