【发布时间】:2020-08-12 00:39:59
【问题描述】:
我在 heroku 应用程序上部署了我的 MERN 项目,但是当我尝试提交表单时,它在控制台中向我发送此错误:
在 'localhost:8000/api/products' 从源访问 XMLHttpRequest “https://thebeuter.herokuapp.com”已被 CORS 政策阻止: 跨源请求仅支持协议方案:http, 数据,铬,铬扩展,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]);
【问题讨论】:
-
您的端点需要访问您部署的服务器,而不是本地主机。阅读
CORS -
如何修复我的帖子。(localhost:8000...)
-
尝试从帖子请求中删除
localhost:8000 -
.post在取出 localhost:8000 后工作正常,但.get它给了我这个错误TypeError: e.map is not a function -
哪个
.get()调用引发了错误?