关于访问控制允许来源的问题

时间:2020-06-25 14:39:42

标签: reactjs api axios

我在浏览器控制台上收到此错误。

CORS策略已阻止从来源“ http:// localhost:8002”访问“ http:// localhost:8069 / api / login_prakriti_user”处的XMLHttpRequest:对预检请求的响应未通过访问权限检查:请求的资源上没有“ Access-Control-Allow-Origin”标头。

我的webpack文件:

const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports = {
   entry: "./src/App.js",
   output: {
      path: path.join(__dirname, "bundle/js"),
      filename: "index_bundle.js",
      publicPath: "/",
   },
   devServer: {
     inline: true,
     port: 8002,
     historyApiFallback: true,
     disableHostCheck: true,
     proxy: { "/api": { target: "http://localhost:8069", changeOrigin: true } },
   },
   module: {
     rules: [
      {
       test: /\.jsx?$/,
       exclude: /node_modules/,
       loader: "babel-loader",
       query: {
       presets: ["es2015", "stage-0", "react"],
      },
    },
    {
     test: /\.s?css$/,
     use: ["style-loader", "css-loader", "sass-loader"],
    },
    {
     test: /\.(png|jpg|gif)$/,
     loaders: ["url-loader"],
    },
   ],
  },
  plugins: [
    new HtmlWebpackPlugin({
     template: "public/index.html",
    }),
  ],
};

这是我的带有axios功能的JS文件:

path = /api/login_prakriti_user
return axios({
  method,
  url: "http://localhost:8069" + path,
   ...options
}).then((res) => {
if(res.data.success) {
  return res;
} else if(!res.data.tokenSuccess) {
  logout();
  toast.error(res.data.message);
} else {
  return;
}
}).catch((e) => {
  if (e.response && e.response.status === 401){
    toast.error(e.response.data.message);
  } else {
    return e
  }
})
}

我正在python文件中调用此函数。

  @http.route('/api/login_prakriti_user', methods=['POST'], type='http', auth='public', website=True, csrf=False, cors="*")

  def user_login(self, **kwargs):

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

更新的JS文件:

仅在url中传递函数名称,而在webpack文件中传递代理。

 return axios({
    method,
    url: /api/login_prakriti_user,
     ...options
    }).then((res) => {
    if(res.data.success) {
      return res;
    } else if(!res.data.tokenSuccess) {
      logout();
      toast.error(res.data.message);
    } else {
       return;
   }
   }).catch((e) => {
     if (e.response && e.response.status === 401){
      toast.error(e.response.data.message);
     } else {
       return e
     }
   })
  }
相关问题