gpt4 book ai didi

javascript - ReactJS获取外部Json

转载 作者:行者123 更新时间:2023-12-03 03:43:41 25 4
gpt4 key购买 nike

我想用 Reactjs 创建一个组件来从 url 获取 json,我尝试使用(Axios、Fetch、Jsonp...)和其他包。
使用 Axios 和 Jsonp 我遇到了 CORS 错误,无法解决该问题。
通过 Fetch,我可以使用 'mode': 'no-cors' 禁用 cors,但不会收集任何数据。

这是我的代码:

getData() {

const header = {
'Access-Control-Allow-Origin': '*',
'mode': 'no-cors'
};

this.serverRequest = fetch('https://www.cryptopia.co.nz/Exchange/GetTradePairChart?tradePairId=5355&dataRange=2&dataGroup=60', header)
.then(response => response.json())
.then(json => {
console.log(json);
this.setState({
altcoinsData: json
});
}).catch(e => {
console.log(e);
});
}

错误:

语法错误:输入意外结束 在 App.js:30 在

最佳答案

如果您使用的是 webpack-dev-server,请在 webpack.config.js 中添加代理服务以避免 CROS。

devServer: {
port: 8080,
stats: 'errors-only',
proxy: {
'/api': {
target: 'http://localhost:20404', //http://localhost:20403/',
secure: false
}
}
}

如果没有,您可以使用 http-proxy-middleware 启动一个 Express 服务器,将 ajax 请求代理到所需的端点。请找到一个包含express和webpack配置的示例server.js。

希望有帮助:)

var webpack = require('webpack');
var Agent = require('agentkeepalive');
var config = require('./webpack.config.js');
var https = require('https');
var proxy = require('http-proxy-middleware');
const express = require('express');
const path = require("path");
const webpackDevMiddleware = require('webpack-dev-middleware');

var app = express();
var compiler = webpack(config);

app.use(
'/api',
proxy({
target: 'http://10.134.116.186:1521/',
changeOrigin: true,
agent: new Agent({
maxSockets: 100,
keepAlive: true,
maxFreeSockets: 10,
keepAliveMsecs: 100000,
timeout: 6000000,
keepAliveTimeout: 90000 // free socket keepalive for 90 seconds
})
})
);
app.use(
'/dist',
proxy({
target: 'http://localhost:8080/',
changeOrigin: true,
agent: new Agent({
maxSockets: 100,
keepAlive: true,
maxFreeSockets: 10,
keepAliveMsecs: 100000,
timeout: 6000000,
keepAliveTimeout: 90000 // free socket keepalive for 90 seconds
})
})
);
app.use(
webpackDevMiddleware(compiler, {
hot: true,
historyApiFallback: true,
contentBase: config.output.path,
publicPath: config.output.publicPath,
headers: { 'Access-Control-Allow-Origin': '*' }
})
);
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname + '/index.html'));
});

app.listen(7071, 'localhost', function(err, result) {
if (err) {
return console.log(err);
}
console.log('Webpack Dev Server is fired up!!');
});

关于javascript - ReactJS获取外部Json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45508694/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com