node.js - 在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]);
解决方案
这个问题的答案是有env
文件development
和production
用于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 应用程序
推荐阅读
- openstack - OpenStack 连接来自不同项目的两个子网
- reactjs - 使用用户 ID 参数错误提取 Redux 数据 - React / Node / Express
- python - Python日期格式转换为日期时间
- go - Hugo 不使用本地 git 配置
- ubuntu - 在 Ubuntu 20.04 上安装 Elasticsearch 不受支持的版本?
- azure - 无法使用 azure powershell 创建 VM
- reactjs - 环境变量在生产中不起作用
- html - 由轮廓引起的空白
- android - 从firebase实时数据库中删除项目后,在回收站视图中保持位置不起作用
- mysql - 没有 PHP 的 MySQL 搜索数组