gpt4 book ai didi

javascript - 为什么 ReactJS 仅在本地主机上呈现图表中的数据值?

转载 作者:行者123 更新时间:2023-11-30 10:58:52 25 4
gpt4 key购买 nike

我在 node.js 和 EXPRESS 上创建了 Restful API。

当其他用户尝试使用我的本地 IP 地址查看 JSON 格式的数据时,一切都很好。

当其他用户尝试使用我的本地 ip 地址打开我的 ReactAPP 时,图表是空的。

当我打开我的 ReactAPP 时,图表中充满了数据值?

可能是我在渲染时出错或者...我不知道...

我的代码:

import React from 'react';
import Select from "react-dropdown-select";
//import Calendar from 'react-calendar';


import './aladin.css';
import {
ComposedChart,
Bar,
BarChart,
Area,
Line,
XAxis,
YAxis,
CartesianGrid,
Tooltip,
Legend
} from 'recharts';

class Aladin extends React.Component {


state = {
date: new Date(),
}

onChange = date => this.setState({ date })

constructor(props) {
super(props);
this.state = {
loading: true,
dataAPI: null,
temp: null,
dats: null,
};
}


async componentDidMount() {
const url = "http://localhost:8000/?date=2019-10-20&station=41027&daysForward=2";
const response = await fetch(url);
let data = await response.json();
this.setState({ dataAPI: data.aladinModel[0], loading: false });
this.setState({ temp: data.aladinModel[0], loading: false });
this.setState({ dats: data.aladinModel[0], loading: false });
//console.log(this.state.temp[1].TA);
//console.log(this.state.dats[1].DATS);
//console.log(this.state.date);
}

render() {

return (
<div className="grid-container-aladin">

<div className="grid-all-items">

<div className="header-aladin">
<div className="select">

<Select />
<Select />
</div>
<p><b>TA - Температура с данни на 3 часа, RH - Влажност на въздуха с данни от 3 часа, WS - Скорост на вятъра с данни от 3 часа.</b></p>
<p><b>SR - Сняг с данни на 3 часа, RR - Дъжд с данни от 3 часа, DATS - Дата избрана от потребителя.</b></p>
<ComposedChart width={800} height={400} data={this.state.dats} margin={{
top: 20, right: 0, left: 0, bottom: 20,
}}>
<CartesianGrid stroke='#f5f5f5' />
<XAxis dataKey="DATS" />
<YAxis />
<Tooltip />
<Legend />
<Area type='monotone' dataKey='TA' fill='#f56200' stroke='#f56200' />
<Line type="monotone" dataKey="RH" stroke="#8884d8" />
<Bar dataKey='WS' barSize={20} fill='#00ff0d' />
<Bar dataKey='SR' barSize={20} fill='#f70000' />
<Bar dataKey='RR' barSize={20} fill='#003cff' />
<Bar dataKey="DATS" stackId="a" fill="#000000" />
</ComposedChart>
</div>



<div className="grid-item-aladin">
<p><b> ТА - Температура с данни на 3 часа:<br />DATS - Дата избрана от потребителя:</b></p>
<BarChart
width={800}
height={400}
data={this.state.dats}
margin={{
top: 20, right: 0, left: 0, bottom: 20,
}}
>
<CartesianGrid strokeDasharray="3 3" />
<XAxis dataKey="DATS" />
<YAxis />
<Tooltip />
<Legend />
<Bar dataKey="TA" stackId="a" fill="#f56200" />
<Bar dataKey="DATS" stackId="a" fill="#303030" />
</BarChart>
</div>
<div className="grid-item-aladin">
<p><b> WS - Скорост на вятъра с данни на 3 часа:<br />DATS - Дата избрана от потребителя:</b></p>
<BarChart
width={800}
height={400}
data={this.state.dats}
margin={{
top: 20, right: 0, left: 0, bottom: 20,
}}
>
<CartesianGrid strokeDasharray="3 3" />
<XAxis dataKey="DATS" />
<YAxis />
<Tooltip />
<Legend />
<Bar dataKey="WS" stackId="a" fill="#f56200" />
<Bar dataKey="DATS" stackId="a" fill="#303030" />
</BarChart>
</div>
<div className="grid-item-aladin">
<p><b> RH - Влажност на въздуха с данни на 3 часа:<br />DATS - Дата избрана от потребителя:</b></p>
<ComposedChart width={800} height={400} data={this.state.dats}
margin={{
top: 20, right: 0, left: 0, bottom: 20,
}}
>
<XAxis dataKey="DATS" />
<YAxis />
<Tooltip />
<Legend />
<CartesianGrid stroke='#f5f5f5' />
<Area type='monotone' dataKey='RH' fill='#8884d8' stroke='#8884d8' />
<Bar dataKey="DATS" stackId="a" fill="#303030" />
</ComposedChart>
</div>
<div className="grid-item-aladin">
<p><b> APRESS - Атм. налягане с данни на 3 часа:<br />DATS - Дата избрана от потребителя:</b></p>
<ComposedChart width={800} height={400} data={this.state.dats}
margin={{
top: 20, right: 0, left: 0, bottom: 20,
}}
>
<XAxis dataKey="DATS" />
<YAxis />
<Tooltip />
<Legend />
<CartesianGrid stroke='#f5f5f5' />
<Area type='monotone' dataKey='APRES' fill='#8884d8' stroke='#8884d8' />
<Bar dataKey="DATS" stackId="a" fill="#303030" />
</ComposedChart>
</div>
<div className="grid-item-aladin">
<p><b> RR - Валеж с данни на 3 часа:<br />DATS - Дата избрана от потребителя:</b></p>
<BarChart
width={800}
height={400}
data={this.state.dats}
margin={{
top: 20, right: 0, left: 0, bottom: 20,
}}
>
<CartesianGrid strokeDasharray="3 3" />
<XAxis dataKey="DATS" />
<YAxis />
<Tooltip />
<Legend />
<Bar dataKey="RR" stackId="a" fill="#4287f5" />
<Bar dataKey="DATS" stackId="a" fill="#303030" />
</BarChart>
</div>
<div className="grid-item-aladin">
<p><b> SR - Сняг с данни на 3 часа:<br />DATS - Дата избрана от потребителя:</b></p>
<BarChart
width={800}
height={400}
data={this.state.dats}
margin={{
top: 20, right: 0, left: 0, bottom: 20,
}}
>
<CartesianGrid strokeDasharray="3 3" />
<XAxis dataKey="DATS" />
<YAxis />
<Tooltip />
<Legend />
<Bar dataKey="SR" stackId="a" fill="#4287f5" />
<Bar dataKey="DATS" stackId="a" fill="#303030" />
</BarChart>

</div>
</div>
</div>
);
}
}



export default Aladin;

我认为错误不在 API 中,因为用户看到的是 JSON 格式的数据。

我还在 node.js 和 EXPRESS 上上传我的 API 代码:

代码:

// Create express app
var express = require("express")
var app = express()
var mysql = require('mysql')
var express = require("express")
var cors = require('cors')


app.use(cors())


// Server port
var HTTP_PORT = 8000

// Start server
app.listen(HTTP_PORT, () => {
console.log("Server running on port %PORT%".replace("%PORT%",HTTP_PORT))
});

var con = mysql.createConnection({
host: "192.168.1.1",
port: "1456",
user: "user",
password: "pass"
});

let aladinModel='';


/*
con.connect(function(err) {
if (err) throw err;
//Select all customers and return the result object:

con.query("CALL aladin_surfex.Get_mod_cell_values_meteogram('2018-08-01',41027,5)", function (err, result, fields) {
if (err) throw err;
console.log(result);
aladinModel = result;
});
});
*/


// Root endpoint
app.get("/", (req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*');
const date = req.query.date;
const station = req.query.station;
const daysForward = req.query.daysForward;

try {
const query = `CALL aladin_surfex.Get_mod_cell_values_meteogram('${date}', ${station}, ${daysForward})`;
con.query(query, function (err, result, fields) {
if (err) throw err;
aladinModel = result;
});
res.json({aladinModel})
} catch(error){
console.log("Error query database!!!");
}

});


app.use(function(req, res){
res.status(404);
});

最佳答案

我认为他们看不到数据,因为当他们使用您的 IP 地址访问您的应用时,他们会访问 UI。但是由于您在代码中提到了 localhost:8000,并且因为 UI 代码是从他们的浏览器执行的,所以他们将尝试使用此 IP 地址 (locahost == 127.0.0.1) 而不是您的来获取数据.

const url 变量的值应该与客户端访问和使用的 IP 地址相关。

首先,你可以试试这个:

const url = "http://" + window.location.hostname + ":8000/?date=2019-10-20&station=41027&daysForward=2";

也许其他用户在这个改变之后会遇到 CORS 问题:

Cross-Origin Resource Sharing (CORS) is a mechanism that uses additional HTTP headers to tell browsers to give a web application running at one origin, access to selected resources from a different origin. A web application executes a cross-origin HTTP request when it requests a resource that has a different origin (domain, protocol, or port) from its own.

https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

如果发生这种情况,您可以将后端配置为接受 CORS 请求。

关于javascript - 为什么 ReactJS 仅在本地主机上呈现图表中的数据值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58815324/

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