I'm working on project that use Node Express and React. Here's my project's dir I would like to send a var which is an array of JSon from my app.js to index.js.
How should i do?
Ask questions if you need more informations.
I'm working on project that use Node Express and React. Here's my project's dir I would like to send a var which is an array of JSon from my app.js to index.js.
How should i do?
Ask questions if you need more informations.
export a function that takes the array as an argument.
index.js
module.exports = function(array) {
console.log(array);
}
and call it from app.js
var index = require('./index');
index([]);
You should not directly import variables from server. Instead in your App, retrieve that data via api call.
Anyway, when you need to use data from another file, use import and export statement
For example
bookstore.js
export default const = [
{isbn: '1234-4567-6544', name: 'Learn React'}
]
app.js
import books from './bookstore';
// use books here
I believe you're asking more about how to send data between client and server.
With express, you can create a route, that sends the JSON var via a get request made by your react client.
Heres a bit of example code:
//Serverside (EXPRESS)
var app = express();
var myJson = { "foo": "bar" };
app.get('/myjson', function(req, res) {
res.send(JSON.stringify(myJson));
});
//CLIENTSIDE (REACT)
...
import axios from 'axios';
...
...
myFunction() {
var serverAddress = "<insertserveraddresshere>"
axios.get(serverAddress+`/myjson`)
.then(res => {
console.log(res); //json should be here
});
}
...
Thx you three for your time. I think matt is closest to what i want to do.
I tried this:
//Serverside (EXPRESS)
...
app.get('/jsonSansAnonymous', function (req,res){
res.send(JSON.stringify(jsonSansAnonymous));
});
...
//CLIENTSIDE (REACT)
...
var serverAddress = "http://localhost:9000";
axios.get(serverAddress + `/jsonSansAnonymous`)
.then(res => {
alert(res);
});
...
Did i do something wrong? maybe my var serverAdress wasn't what you were talking about. My var jsonSansAnonymous isn't just an Json, but an Array of Json.
Thx again for your help.