I'm working on a ReactJS project and I'm using Axios to connect to my NodeJS backend using express and a MongoDB Database.
I have a button in my render function that when clicked calls the following function:
getInfo() {
Axios.get('http://localhost:9000/getMyData')
.then(res => console.log(res));
}
This works fine, it connects, queries my database and I can see the results in my console.
BUT
If I try to set the state with this result, it is undefined.
For example:
getInfo() {
Axios.get('http://localhost:9000/getMyData')
.then(res => this.setState({data: res})); // or res.data based on the way I want to save it
}
I get a 304 response instead of a 200 response, and React says that res is undefined.
I do not understand what is going on here, why can I console log the response, but I can't store it.
Can someone please explain to me what I am doing wrong, and how I can store the data?
Thank you.
Related
On node js, I'm trying to do a post request, before that though I want to test if a get request can give me a response.
On my browser, I have the following URL:
http://127.0.0.1:3000/home/finishpage/client/index.html
Now when I set up a get request, nothing comes back, e.g.
app.get("/home/finishpage/client/index.html", (req,res)=>{
console.log("testing get request")
res.sendFile(path.join(__dirname,"/index.html")) //dont mind this
})
The console.log doesn't print in this instance, which means I'm not getting the res I want.
Now if I add a fake rout like this:
app.get("/home/finishpage/client/index.html/fake", (req,res)=>{
console.log("testing")
res.sendFile("test")
})
and go to my browser and search:
http://127.0.0.1:3000/home/finishpage/client/index.html/fake
This give me a response, and excutes the console.log("testing") command.
What am I not understanding.
you need to serve static files for express app
app.use(express.static({folderPath}));
This is a function on my front-end that makes the request.
function postNewUser(){
fetch(`http://12.0.0.1:8080/users/test`, {
method: 'POST',
body: {nome: name, email: "test#test.com.br", idade: 20}
})
}
This is my back-end code to receive the request.
router.post('/users/:id', koaBody(), ctx => {
ctx.set('Access-Control-Allow-Origin', '*');
users.push(ctx.request.body)
ctx.status = 201
ctx.body = ctx.params
console.log(users)
})
For some unknown reason I receive nothing. Not even a single error message. The "console.log()" on the back-end is also not triggered, so my theory is that the problem is on the front-end.
Edit
As sugested by gnososphere, I tested with Postman, and it worked. So now i know the problem must be on the fron-end code.
You can try your backend functionality with Postman. It's a great service for testing.
the request would look something like this
If the problem is on the frontend, double check your fetch method by posting to a website that will return data and logging that in your app.
I'm going to use the following code as an example to frame my question. It's basically just the code required to pull a list of to dos from an SQLite3 database:
So, there's an axios request in the front end:
useEffect(() => {
axios.get('http://localhost:3001/todo', {})
.then(res => {
setTodoList(res.data)
})
.catch(err => {
console.log(err)
})
}, [])
...which links to the following function in the back end:
server.get('/todo', (req,res) => {
// res.json(testData)
const todos = db('todos') //this is shorthand for 'return everything from the table 'todos''
.then(todos => {
return res.json(todos)
})
})
..the data from this GET request is then rendered within a react component, as a list of text.
I'm just confused about the flow of data - when is it HTTP, when is it JSON, what form does the data come out of the database as, and how is it that these different protocol/languages can talk to each other?
I get the overall principle of a GET request and async functions, I just don't get what's going on under the hood. Thanks!
That's a lot of questions about basic issues. But here are some answers. Firstly, you can simplify the server function as:
server.get('/todo', (req, res) => {
db('todos').then(todos => res.json(todos));
});
The data from the db is a Javascript array by the time you are dealing with it in Express. res.json converts it into JSON, which is of course, just a string.
Express creates an HTTP response, which consists of some headers (key value pairs such as Content-Length: and so on) followed by a body, which in your case is just a JSON blob, a string. That response object is sent over the network via HTTP.
The browser receives the response and axios is kind enough to handle the grunt work of reading the headers and turning your JSON back into a Javascript array/object which can then be handled inside React.
The part I can't answer is "how is it that these different protocol/languages can talk to each other", because that is very complex and the question is not well defined. There are many network layers involved.
I am trying implement REST API using REACT AND NODE. How to get JSON from front end(REACT JS)drag and drop images in template ex."https://www.canva.com/templates/" to store JSON in Mongodb using NODE JS.
Thanks in advance
You can use fetch api to call a particular route and send data along with it to nodejs backend.
You just need to do simply like this:
async function sendData(){
let res = await fetch(url, {
method: 'POST',
mode: 'CORS',
body: {}, //the json object you want to send
headers: {}, //if required
}
)
}
Hope this helps!
Since you asked how to send JSON to node.js I'm assuming you do not yet have an API that your front end can use.
To send data to the back end you need to create an API that accepts data.
You can do this quickly and easily using express.js.
Once the server is running and it has an endpoint to send data to, you can create a request (e.g. when sending data it should be a POST request).
This can be done in many different ways, although I would suggest trying axios.
Hope this helped.
Check the example to get the Json value and update it.
axios.get('https://jsonplaceholder.typicode.com/todos/'+ this.props.id + '/')
.then((res) => {
this.setState({
// do some action
});
})
.catch(function (error) {
console.log(error);
});
i am beginner so i apologize if my question isn't relevant or easy to fix, but i couldn,t fix my issue yet, for 4 days.
I am working on an api, which will receive data from angular form, then store it with sequelize on a mariadb table.
When i submit my form, which would through the url, post it in the table through the api, i can see that the req.body is defined, and it reachs the api, but yet i have and error in my angular http post which is thrown(error 500).
With postman, i see that my url isn t reachable, i can't figure out so if my error comes from the post angular, or the backend with my model, even if error 500 is for back end.
I tried to redefine my sequelize model, parse and stringify the object i send, try others url...but nothing works.
So here is my function called when the form is submitted,the function formatrequestschedulest return the object i want to post.
onSubmitScheduled(){
let OndemandScheduledRequest = this.formatRequestScheduled(this.selectedHotel, this.selectedCheckInDate, this.selectedCheckOutDate, this.selectedNumber, this.selectedCurrency, this.selectedReportName, this.selectedUser, this.selectedEmail, this.selectedFormat);
console.log(OndemandScheduledRequest);
this.saveScheduledRequest(OndemandScheduledRequest);
return this.openDialog();
}
saveScheduledRequest(onDemandScheduledRequest: OnDemandScheduledRequest){
this.http.post('/api/ScheduledReport', JSON.stringify(onDemandScheduledRequest), {headers: {'Content-Type': 'application/json'}})
.subscribe(res=>{ console.log(res
)
console.log('ok')},
(err) =>
console.log('an error'))
/*console.log(err))*/
}
And here is my api:
var request= require('../controller/ondemandscheduledrequests');
var router = express.Router();
router.get('/getreport',request.create);
router.post('/ScheduledReport',request.create);
I can provide also the error i get, but i don't know if i can join a picture to the question.
I just want to have my form data store to my table, but i get an error 500 instead.
this is the error i get
Use pipe like below and try once
this.http.post('/ScheduledReport', JSON.stringify(onDemandScheduledRequest).pipe().subscribe(val => {
console.log(val, "service");
, {headers: {'Content-Type': 'application/json'}})}