Send data react axios - reactjs

Send data React to Node
If send data with axios.
is it correct?
react:
let data = {pp: number};
axios.post('http://localhost:3001/number', {
body: data
}). then((response) => {
console.log('data submitted success');
}).catch((error) => {
console.log('got err', error);
});
this in server
router.post('/', function (req, res) {
var countValue = req.body;
console.log('CountValue is', countValue);
});

It seems you need to put bodyParser.json() in your middleware.
For example:
app.use(bodyParser.json());
After that, you could use below code as your HTTP response in the controller.
res.status(200).json({ results: countValue });
I believe you don't need to use JSON.stringify(countValue)
Feel free to share more details for us :)

Related

Parsing fetched XML with react-xml-parser

I am first fetching xml data from an external api in my backend and then trying to send that to the frontend.
Backend (server):
app.get("/api", (req, res) => {
var request = require('request');
var options = {
'method': 'GET',
'url': 'http://link',
'headers': {
}
};
request(options, function (error, response) {
console.log("TEST1")
console.log(response.body)
if (error){
console.log("TEST2")
res.status(404).write("NO LUCK");
}
console.log("TEST3")
res.status(200).write(response.body);
});
});
The xml appears in my terminal correctly. TEST1 and TEST2 do too.
Frontend (client):
import XMLParser from 'react-xml-parser';
useEffect(() => {
fetch("/api")
.then(res => res.text())
.then(data => {
var xml = new XMLParser().parseFromString(data);
console.log(xml)
})
.catch(err => console.log(err));
}, []);
Nothing appears on the console. I got the frontend code from this stack overflow post.
fetch("/api")
.then((res) => res.body)
.then((data) => console.log(data));
If I log the response body like this I get a ReadableStream object. This is the only functionality I've been implementing so far so nothing should be interfering with it. When I try different approaches I keep needing to restart React or it will load endlessly when I refresh.
When I open http://localhost:3001/api I can see the xml data I'm trying to transfer.
Still not sure why it didn't work before but it works with this.
Frontend (client):
import axios from "axios";
axios.get('/api')
.then(xml => {
console.log(xml.data);
})
Backend (server):
app.get('/api', (req, res) => {
var axios = require('axios');
var config = {
method: 'get',
url: 'http://link',
headers: {'Content-Type': 'application/xml'}
};
axios(config)
.then(function (response) {
res.json(response.data);
})
.catch(function (error) {
console.log(error);
})
})

Post the following data using axios with help of picture

With the help of this image I wish to construct an api call using axios post. While I am trying to get the data I'm facing error although the api is hitting the backend.
This is my code:
login = async() => {
let params = {
email: "abc#gmail.com",
password: "12342346667"
}
let res0 = await axios.post('https://example.com/authentication/api/Login', params)
.catch((error) => console.log('error', error));
}
Postman post method:
I am new to React.
Try this way
axios.post('https://example.com/authentication/api/Login', {
email: "abc#gmail.com",
password: "12342346667"
})
.then(function response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});

Send parameter not in URL to API

I send a request to my API with advancedFetch. This works, however, I want to know if it is possible to send a parameter without defining it in the URL. Are there any smart ways of doing this?
I tried researching it but I'm not sure I'm using the right keywords for what I'm trying to do.
This is where I set off my request (the value is from a modal input field):
setNewUserName(userName) {
this.setState({newUserName: userName});
advancedFetch('/api/users', {
method: 'POST',
body: JSON.stringify({}),
credentials: 'include',
// I've tried sending the param here
userName: userName,
headers: {
'Content-Type': 'application/json'
}
})
.then(() => {
this.loadUsers();
})
.catch(err => {
//error handling
});
}
In my controller I defined the route and implemented function like this:
index.create = (req, res, next) => {
let userName = req.params.userName;
console.log(userName);
user
.create(userName)
.then((response) => {
res.send(response);
})
.catch((err) => {
next(err);
});
};
router.post('/users', index.create);
And then in my service.js I write the data to my database:
create: function(userName){
userName = userName
return query(`INSERT INTO ${tableName} (user) VALUES (?, ?)`, [1, userName])
.catch(err => {
app.logger.error('[Users] failed to create a user', err.message);
return Promise.reject(new Error('failed to create user'));
});
},
I always get an undefined userName, do I have to create a route with the value at the end?
You're receiving userName as undefined, because you're sending the request with JSON-encoded data, rather than URL parameters and the same logic doesn't apply for that case.
Luckily there's an easy way to solve your problem, using expressjs body-parser package. It's very easy to use.
This is how you initialize it:
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
// parse application/json
app.use(bodyParser.json())
And this is how you would read "userName" in your router function:
index.create = (req, res, next) => {
let userName = req.body.userName;
console.log(userName);
user
.create(userName)
.then((response) => {
res.send(response);
})
.catch((err) => {
next(err);
});
};
And btw, when you're calling advancedFetch, you should actually be doing this:
body: JSON.stringify({newUserName: userName}),
Yes, you can actually do it this way:
In the frontend call you can send the parameter through the body like so
body: JSON.stringify({userName: userName})
And then in your controller what you want to do is to directly access the paramter from the body:
let userName = req.body.userName;
And now it's not undefined anymore :)

Trying to fetch API I created to react component

So I created test API and added few test records to the DB.
Now when I wanted to fetch the data in react component I'm getting this error
Unhandled Rejection (SyntaxError): Unexpected token < in JSON at position 0
when I try to console.log the data to see if it works. I asume it has something to do with the fact, that I run the API server on port 8080 and react app on 3000 (when I switched api to 3000 and clicked "back arrow" I saw a console.log with the data, but when I refreshed the site it realised the API is "occupying" this URL now).
How can I fix that? Here is the important part of the code, if I need to post more please do let me know.
API (app\src\apiTest\index.js):
const express = require('express');
const routes = require('./api.js');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const app = express();
//connect to mongodb
mongoose.connect('mongodb://localhost/drugDB');
mongoose.Promise = global.Promise;
//serving files (folder name)
app.use(express.static('../../../src'));
app.use(bodyParser.json());
//initialize routes
app.use('/api', routes);
//error handling middleware
app.use(function(err, req, res, next){
res.send({error: err.message})
})
app.listen(process.env.port || 8080, function(){
console.log('listening')
})
2nd file in API
const express = require('express');
const Drug = require('./models/drug');
const router = express.Router();
//get list of drugs
router.get('/leki', function (req, res) {
Drug.find({}).then(function(drugs){
res.send(drugs);
})
})
router.post('/leki', function (req, res, next) {
Drug.create(req.body).then(function (drug) {
res.send(drug);
}).catch(next);
})
router.put('/leki/:id', function (req, res, next) {
Drug.findByIdAndUpdate({ _id: req.params.id }, req.body).then(function () {
Drug.findOne({ _id: req.params.id }).then(function (drug) {
res.send(drug);
})
})
})
router.delete('/leki/:id', function (req, res, next) {
Drug.findByIdAndRemove({ _id: req.params.id }).then(function (drug) {
res.send({ type: drug })
});
})
module.exports = router;
react component (app\src\components\MainPanel\panel.js):
componentDidMount(){
fetch('/api/leki').then(function(data){
console.log(data.json());
})
}
The error is suggesting that you're not receiving JSON back in response. Which is the case because inside of your leki endpoint you're using res.send(drug); which sends data back as HTML, change it to res.json({data: drug}) and then inside of componentDidMount:
componentDidMount(){
fetch('/api/leki', {
method: 'GET',
headers: {
'Accept': 'application/json',
}
}).then(function(response){
return response.json();
}).then(function(data) {
console.log(data.drug)
})
}
Try this:
componentDidMount() {
fetch('/api/leki')
.then(function (resolve) { return resolve.json(); })
.then(function (resolveJson) {
console.log(resolveJson);
});
}
Look at this for more information:
https://developers.google.com/web/updates/2015/03/introduction-to-fetch
You need to allow Cross Origin requests by setting a header in your response in the backend.
Place this code where you send your response:
res.set('Access-Control-Allow-Origin', 'http://localhost:3000');

Axios GET request fails to hit endpoint without params object

I am making a request to a custom endpoint...
VideoAPI.get('/api/getVideo/:id', function(req, res){
console.log('FROM URL STRING', req.params)
console.log('FROM PARAMS OBJECT', req.query)
res.end()
}
If if make an Axios post like so, it never hits the endpoint and I get a 300 status response client side:
axios.get(`/api/getVideo/2`)
.then( res => {
console.log(res)
})
But if I make the call like so, it hits the endpoint as expected, even if the params object is completely irrelevant data:
axios.get(`/api/getVideo/2`, {
params : {
bogus: 'WTF'
}
})
.then( res => {
console.log(res)
})
My console will read:
FROM URL STRING { id: '2' }
FROM PARAMS OBJECT { bogus: 'WTF' }
What am I not understanding here?

Resources