在Heroku上部署后做出反应时出现网络错误

时间:2020-08-12 00:39:59

标签: node.js reactjs heroku

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

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

这是我的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]);

0 个答案:

没有答案