Sco*_*son 19 javascript node.js reactjs isomorphic-javascript axios
我使用React和Express遇到了同构JavaScript应用程序的问题.
我正在尝试使用axios.get在我的组件安装时发出HTTP请求
componentDidMount() {
const url = 'http://ufc-data-api.ufc.com/api/v3/iphone/fighters/title_holders';
axios.get(url).then( res => {
//use res to update current state
})
}
Run Code Online (Sandbox Code Playgroud)
我从API获得状态200 res,但我没有得到任何响应数据并在我的控制台中收到错误
XMLHttpRequest cannot load http://ufc-data-api.ufc.com/api/v3/iphone/fighters/title_holders.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://localhost:3000' is therefore not allowed access.
Run Code Online (Sandbox Code Playgroud)
但是,如果我在server.js中发出请求
const url = 'http://ufc-data-api.ufc.com/api/v3/iphone/fighters/title_holders';
axios.get(url).then(res => {
//console.log(res);
});
Run Code Online (Sandbox Code Playgroud)
它工作正常,我在服务器启动时获得响应数据.这是实际API的问题还是我做错了什么?如果这是一个CORS问题,我猜测server.js中的请求也不起作用?谢谢!
小智 17
使用名为Allow-Control-Allow-Origin的Google Chrome扩展程序:*.它会在您的应用程序中动态修改CORS标头.
azi*_*ium 16
CORS是一种浏览器功能.服务器需要选择加入CORS以允许浏览器绕过同源策略.您的服务器不会受到相同的限制,并且能够使用公共API向任何服务器发出请求.https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
在服务器上创建一个端点,启用CORS,可以充当Web应用程序的代理.
ali*_*ran 11
应该在服务器端启用 CORS!如果您无法在服务器上激活它(例如使用外部 API),请创建一个中间件React -> Middleware -> Orginal Server
。
创建一个 Node.js 项目(中间件)并在app.js
.
const express = require("express");
var cors = require('cors')
const app = express();
app.use(cors());
const { createProxyMiddleware } = require('http-proxy-middleware');
app.use('/api', createProxyMiddleware({
target: 'http://localhost:8080/', //original url
changeOrigin: true,
//secure: false,
onProxyRes: function (proxyRes, req, res) {
proxyRes.headers['Access-Control-Allow-Origin'] = '*';
}
}));
app.listen(5000);
Run Code Online (Sandbox Code Playgroud)
这会将请求传递http://localhost:5000/api/xxx
给原始服务器(例如http://localhost:8080/api/xxx
),并将结果返回给客户端。
更改客户端(React)调用代理获取数据,不会出现CORS错误(只需更改url中的端口即可):
axios.get('http://localhost:5000/api/xxx', //proxy uri
{
headers: {
authorization: ' xxxxxxxxxx' ,
'Content-Type': 'application/json'
}
}).then(function (response) {
console.log(response);
});
Run Code Online (Sandbox Code Playgroud)
运行节点项目node app.js
和反应项目npm start
。
我今天遇到了同样的错误,使用 React 和 Typescript 以及使用 Java Spring boot 的后端,如果你有后端经验,你可以简单地为 CORS 添加一个配置文件。
对于下面的示例,我将 allowed origin 设置为 * 以允许所有内容,但您可以更具体,仅设置像http://localhost:3000这样的 url 。
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
@Configuration
public class AppCorsConfiguration {
@Bean
public FilterRegistrationBean corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/**", config);
FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
bean.setOrder(0);
return bean;
}
}
Run Code Online (Sandbox Code Playgroud)
我有同样的问题。其他答案是正确的,但还有另一种解决方案。您可以设置响应头以允许跨域访问。根据这篇文章,您必须在任何 app.get 调用之前添加以下代码:
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
next();
});
Run Code Online (Sandbox Code Playgroud)
这对我有用:)
//install cors using terminal/command
$ npm install cors
//If your using express in your node server just add
var cors = require('cors');
app.use(cors())
//and re-run the server, your problem is rectified][1]][1]
**If you won't be understood then see below image**
Run Code Online (Sandbox Code Playgroud)
https://i.stack.imgur.com/Qeqmc.png
归档时间: |
|
查看次数: |
56563 次 |
最近记录: |