我已经创建了一个全堆栈的MERN应用程序,我正在尝试将其部署在Heroku上。但是我似乎无法让前端连接到后端。我尝试使用axios对后端进行简单的发布请求:
axios.post("/api/items", { item }).then((res) => {
if (res.status === 200) {
this.setState({ sended: true });
}
});
与此同时,我也在setupPorxy.js中使用来自http-proxy-middleware的代理:
const proxy = require('http-proxy-middleware')
module.exports = function(app) {
app.use(proxy(['/api' ], { target: 'http://localhost:5000' }));
}
在服务器端,我启用了CORS。我还尝试将http://localhost:3000
更改为https://merninschrijvingen.herokuapp.com
:
app.use(function (req, res, next) {
res.setHeader("Access-Control-Allow-Origin", "http://localhost:3000");
res.setHeader(
"Access-Control-Allow-Methods",
"GET, POST, OPTIONS, PUT, PATCH, DELETE"
);
res.setHeader(
"Access-Control-Allow-Headers",
"Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With"
);
next();
});
我还定义了我的客户位置:
app.use("/api/items", items);
const port = process.env.PORT || 5000;
if (process.env.NODE_ENV === "production") {
app.use(express.static("client/build"));
app.get("*", (req, res) => {
res.sendFile(path.resolve(__dirname, "client", "build", "index.html"));
});
}
app.listen(port, () => console.log("Server starter on port " + port));
这是我的带有BaseUrl的axios实例:
import axios from "axios";
const instance = axios.create({
baseURL: process.env.baseURL || "http://localhost:5000/",
});
export default instance;
这是完整的server.js文件:
const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const path = require("path");
const cors = require("cors");
const items = require("./routes/api/items");
const app = express();
//Bodyparser Middleware
app.use(bodyParser.json());
app.enable("trust proxy");
app.use(cors());
app.use(function (req, res, next) {
res.setHeader(
"Access-Control-Allow-Origin",
"https://merninschrijvingen.herokuapp.com"
);
res.setHeader(
"Access-Control-Allow-Methods",
"GET, POST, OPTIONS, PUT, PATCH, DELETE"
);
res.setHeader(
"Access-Control-Allow-Headers",
"Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With"
);
next();
});
//DB Config
const db = require("./config/keys").mongoURI;
//Connect to Mongo
mongoose
.connect(process.env.MONGODB_URI || db, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => console.log("MongoDB Connected"))
.catch((error) => console.log(error));
//Use Routes
app.use("/api/items", items);
const port = process.env.PORT || 5000;
if (process.env.NODE_ENV === "production") {
app.use(express.static("client/build"));
app.get("*", (req, res) => {
res.sendFile(path.resolve(__dirname, "client", "build", "index.html"));
});
}
app.listen(port, () => console.log("Server starter on port " + port));