I am new to reactjs
and expressjs
. How do I get the data from reactjs
and store it in a variable.
So far I am able to do res.send
the data.
app.get('*', (req, res) => {
const data = {hello: world};
res.send(data);
});
This sends the data to the browser and displays but I want to just save the data to a variable instead of displaying it.
You can in your React Component do something like:
import React, { Component } from 'react';
import './App.css';
class App extends Component {
constructor(){
super();
this.state ={users: []};
}
componentDidMount() {
fetch('/users')
.then(users => {
console.log(users);
this.setState({ users })
});
}
render() {
return (
<div className="App">
<h1>Users</h1>
{this.state.users.map(user =>
<div key={user.id}>user: {user.name} Password: {user.password}</div>
)}
</div>
);
}
}
export default App;
Assuming the object you're interested in called "users" (* You need to change your JSX according to your object fields for sure, to test this)
This is React.js example
import axios from 'axios'
click () {
axios.get('yourAPIAdress')
.then(response => console.log(response))
}
and this is your node.js example code;
const https = require('https');
https.get('yourAPIAdress', (resp) => {
let data = '';
// A chunk of data has been recieved.
resp.on('data', (chunk) => {
data += chunk;
});
// The whole response has been received. Print out the result.
resp.on('end', () => {
console.log(JSON.parse(data).explanation);
});
}).on("error", (err) => {
console.log("Error: " + err.message);
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.