Reactjs 访问控制问题允许来源
我在浏览器控制台上遇到此错误 访问位于“”的XMLHttpRequesthttp://localhost:8069/api/login_prakriti_user“起源”http://localhost:8002'已被CORS策略阻止:对飞行前请求的响应未通过访问控制检查:请求的资源上不存在'access Control Allow Origin'标头 我的网页包文件:Reactjs 访问控制问题允许来源,reactjs,api,axios,Reactjs,Api,Axios,我在浏览器控制台上遇到此错误 访问位于“”的XMLHttpRequesthttp://localhost:8069/api/login_prakriti_user“起源”http://localhost:8002'已被CORS策略阻止:对飞行前请求的响应未通过访问控制检查:请求的资源上不存在'access Control Allow Origin'标头 我的网页包文件: const path = require("path"); const HtmlWebpackPlugin
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):
任何帮助都将不胜感激。更新的JS文件:
在url中只传递函数名,在网页包文件中传递代理
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
}
})
}
您需要在服务器端禁用CORS。代理设置意味着您需要使用与前端相同的域,因此
http://localhost:8002/api/login_prakriti_user
相反。@GuyIncognito我不能用端口8002调用同一个域,因为python API在8069上工作。我正在8069上运行python odoo服务器。是的,您已经设置了一个代理,它将对localhost:8002/api的调用重定向到localhost:8069/api(proxy:{/api):{target:http://localhost:8069“,changeOrigin:true}}
)。这就是代理的全部目的。@guycongnito我已经应用了这个解决方案,但是忘了从JS函数中删除。谢谢你的帮助。请帮我一个忙,请在我的答案上打勾或投赞成票。