在生产环境上与CORS的问题
我有一个在本地运行良好的React应用程序。我可以毫无问题地到达API服务器。问题是当我将代码推向生产环境时,我会发现这些错误与CORS有关的错误
“访问xmlhttprequest at 'https://xxxx-private.xxx.se/api/v1/products'来自原始 'https://xxxx-private.xxxx.se'已被CORS策略阻止:否 请求的“访问控制”标头 资源。”
我尝试在我的package.json文件中添加代理,但这并没有解决问题。我正在使用Axios进行API调用。
示例的API call call call
import axios from 'utils/axios';
import {
GET_PRODUCTS,
GET_PRODUCTS_SUCCESS,
GET_PRODUCTS_ERROR,
ADD_PRODUCT_SUCCESS,
ADD_PRODUCT_ERROR,
UPDATE_PRODUCT_SUCCESS,
UPDATE_PRODUCT_ERROR,
REMOVE_PRODUCT_SUCCESS,
REMOVE_PRODUCT_ERROR,
ADD_PRODUCT,
UPDATE_PRODUCT,
REMOVE_PRODUCT,
} from './constants';
export function* getProductsSaga() {
const requestURL = `/products`;
try {
const response = yield call(axios, requestURL);
yield put({ type: GET_PRODUCTS_SUCCESS, response });
} catch (error) {
yield put({ type: GET_PRODUCTS_ERROR, error });
}
}
屏幕截图,我得到的
I have a react application that works well locally. I am able to reach the api server without any issues. The problem is when I push my code to production environment, I get these errors related to CORS that says
"Access to XMLHttpRequest at
'https://xxxx-private.xxx.se/api/v1/products' from origin
'https://xxxx-private.xxxx.se' has been blocked by CORS policy: No
'Access-Control-Allow-Origin' header is present on the requested
resource."
I have tried adding a proxy to my package.json file but that did not resolve the issue. I am using axios to make api calls.
Example of api call
import axios from 'utils/axios';
import {
GET_PRODUCTS,
GET_PRODUCTS_SUCCESS,
GET_PRODUCTS_ERROR,
ADD_PRODUCT_SUCCESS,
ADD_PRODUCT_ERROR,
UPDATE_PRODUCT_SUCCESS,
UPDATE_PRODUCT_ERROR,
REMOVE_PRODUCT_SUCCESS,
REMOVE_PRODUCT_ERROR,
ADD_PRODUCT,
UPDATE_PRODUCT,
REMOVE_PRODUCT,
} from './constants';
export function* getProductsSaga() {
const requestURL = `/products`;
try {
const response = yield call(axios, requestURL);
yield put({ type: GET_PRODUCTS_SUCCESS, response });
} catch (error) {
yield put({ type: GET_PRODUCTS_ERROR, error });
}
}
Screenshot of the error I am getting
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
配置后端中的CORS以将CORS标头添加到服务器中,并给出
https://xxxx-private.xxxx.se
访问服务器响应(这是假设您正在使用node.js作为后端):Configure the CORS in the backend to add the CORS header to the server and give
https://xxxx-private.xxxx.se
access to the server response (This is assuming that you are using Node.js as the backend):