reactjs - 调用api时反应webpack代理cors问题
问题描述
reactjs 中的错误,当通过 webpack 代理连接到后端时,url 不起作用,即使端点正确,也找不到 404。使用打字稿,我正在使用 axios 在 httpservice 页面中获取我的数据。
devServer: {
port: 8083,
historyApiFallback: true,
contentBase: paths.public,
proxy: {
"/api": "http://localhost:8083",
},
headers: {
"Access-Control-Allow-Origin": "*",
https: true,
},
},
mode: "development",
entry: paths.entry,
resolve: {
extensions: [".js", ".jsx", ".ts", ".tsx", ".json"],
alias: {
src: paths.src,
assets: paths.assets,
},
},
output: {
filename: "[name].[chunkhash:8].js",
publicPath: "/",
},
module: {
rules: [
{
test: /\.m?js/,
resolve: {
fullySpecified: false,
},
},
{
test: /\.tsx?$/,
use: "ts-loader",
},
{
test: /\.(png|jpg|gif|svg)$/i,
type: "asset/resource",
},
],
},
plugins: [
new HtmlWebpackPlugin({
inject: true,
template: paths.html,
}),
],
在获取方面,我这样称呼
import http from "./httpServices";
const apiEndpoint = "/api/item";
function itemUrl(id) {
return `${apiEndpoint}/${id}`;
}
export const getItemsFromApi = () => {
return http.get(apiEndpoint);
};
解决方案
您忘记添加 pathRewrite: { '^/api': '' }。代理不会覆盖 api 端点。pathRewrite 将 /api 替换为目标
proxy: {
"/api": {
target: "http://localhost:8083/",
pathRewrite: { "^/api": "" },
},
},
开发服务器文档: https ://webpack.js.org/configuration/dev-server/#devserverproxy
推荐阅读
- java - 抽象类和非抽象类中的构造函数
- python - 从列表中删除第三个元素,直到少于 3 个数字
- visual-studio - 桥接 2 个 docker-compose 解决方案?
- java - 为什么从包含实体查询布尔值时@Formula 总是返回 true?
- ios - 如何在一个collectionView中使用多个项目数组?
- c# - 按多个值过滤集合列
- android - 出现键盘时如何修复EditText的缩小
- spring - 如何使用只有 tokenValue 的 OAuth2RestTemplate?
- python - 根据每个像素的位置有效地应用一个函数
- django - 如何在 django 管理操作的中间页面中从 request.POST 获取所有值