首页 > 解决方案 > 在heroku上部署后反应网络错误

问题描述

我在 heroku 应用程序上部署了我的 MERN 项目,但是当我尝试提交表单时,它在控制台中向我发送此错误:

从源“https://thebeuter.herokuapp.com”访问“localhost:8000/api/products”处的 XMLHttpRequest 已被 CORS 策略阻止:跨源请求仅支持协议方案:http、data、chrome、chrome -扩展,https。Form.jsx:69 错误:XMLHttpRequest.d.onerror (xhr.js:83) 处的 e.exports (createError.js:16) 网络错误

这是我的 server.js:

const express = require("express"),
    app = express(),
    cors = require("cors"),
    port = process.env.PORT || 8000,
    db = "beuter",
    path = require("path"),
    server = app.listen(port, () => console.log(`Listening to on port ${port}`));

app.use(cors());
app.use(express.json());

if (process.env.NODE_ENV === "production") {
    app.use(express.static('beuter/build'))

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

console.log(port)

require("./server/config/database.config")(db);
require("./server/routes/product.route")(app);

这是我的 Form.jsx:

const addProduct = (e) => {
    e.preventDefault();
    const product = {
      title,
      title_url,
      price,
      description1,
      description2,
      description3,
      description4,
      description5,
      img_url1,
      img_url2,
      img_url3,
      img_url4,
      size,
      size2,
      fit,
      fit2,
      category,
    };
    axios
      .post("localhost:8000/api/products", product)
      .then((res) => {
        if (res.data.errors) {
          setErrors(res.data.errors);
        } else {
          navigate("/");
        }
      })
      .catch((err) => console.log(err));
  };

  return (
...
...
...
)

我怎样才能解决这个问题?这是我的项目 github: https ://github.com/nathannewyen/the-beuter

谢谢!

更新:

ShopAllProducts.jsx

  useEffect(() => {
    const fetchItems = async () => {
      setLoading(true);
      const res = await axios.get("http://localhost:8000/api/products");
      setProducts(res.data);
      setLoading(false);
    };
    document.title = `Shop - The Beuter`;
    fetchItems();
  }, [props]);

标签: node.jsreactjsheroku

解决方案


这个问题的答案是有env文件developmentproduction

用于development 创建在.env.development前端应用程序的根文件夹中调用的文件

在此处输入图像描述

.env.development添加这一行

REACT_APP_BASE_URL="http:localhost:5000"

.env.production添加另一行作为

REACT_APP_BASE_URL="https://algorithammer.herokuapp.com"

或您的网站(我在这里展示示例)

现在确保您有一个称为baseURL全局变量的变量

示例:( authAPI.js示例)


exports.baseURL = process.env.REACT_APP_BASE_URL;

Login.js(示例)


import {baseURL} from "./authAPI.js"

 axios
      .post(`${baseURL}/login`, {
        data: "sample data"
      })
      .then((res) => console.log(res))
      .catch((err) => console.log(err));

不要忘记推送更改并再次部署 heroku 应用程序


推荐阅读