Parsing fetched XML with react-xml-parser - reactjs

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);
})
})

Related

Fetch POST request console.log not working correctly

While I can post data to my server, and the server console.log works, I cannot for the life figure out why the client side console.log isn't working. What am I missing here?
The Error: SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data
Status: 200 OK
Request: {"hotSauceId":32,"presentation":5,"viscosityId":3,"spiciness":10,"Flavor_Notes":["Constituent Peppers"],"overall_rating":5,"lovedit":true,"taster_notes":"test"}
Looks json to me?
Submit Handler:
const handleSubmit = (e) => {
e.preventDefault();
fetch('http://jyh:3000', {
method: 'POST',
headers: {'Content-Type':'application/json'},
body: JSON.stringify({
"hotSauceId": sauce,
"presentation": presentation,
"viscosityId": viscosity,
"spiciness": spiciness,
"Flavor_Notes": flavor,
"overall_rating": overall,
"lovedit": loved,
"taster_notes": notes
}),
}).then(res => {
return res.json();
}).then(data => {
console.log(data);
}).catch(err => {
console.log(err);
});
};
Server Code:
app.post('/', async (req, res) => {
await Jyh.create({ // .create is a Sequelize method
hotSauceId: req.body.hotSauceId,
presentation: req.body.presentation,
viscosityId: req.body.viscosityId,
spiciness: req.body.spiciness,
Flavor_Notes: req.body.Flavor_Notes,
overall_rating: req.body.overall_rating,
lovedit: req.body.lovedit,
taster_notes: req.body.taster_notes
}).then(() => {
console.log('req.body: ', req.body);
}).catch((err) => {
console.log(err);
});
});
It should console.log the response in the client console, but instead I receive an error.
Github repository for the client and server app.

Axios delete not working in react js with Authorization token

I am trying to run a delete query with react js. In Postman my delete query is working, but in my code it says no Authorization
I did
console.log(headers)
to check if header is available but still it's not working. I have posted what I have tried
const deletefile = (e) => {
const headers = {
Authorization: `Token ${sessionStorage.getItem("token")}`,
};
console.log(headers);
const Data = {
id: e,
// // stage: "stage9",
// notes: notes,
};
axios
.delete("file/", Data, {
headers: headers,
})
.then(() => {
alert("success submited");
// setRefresh(Refresh + 1);
})
.catch((error) => {
alert(error);
});
Try the headers as so :)
axios
.delete("your_url", {
headers: headers,
data: Data
})

GET Request not working but POST request is working for database query

I am using Express as my backend and for some reason my GET request is not working to query a Postgres database. I am pretty sure I am supposed to use GET request to query the database but can't seem to get it to work. I get the error below.
SyntaxError: Unexpected token < in JSON at position 0
Here is the code for the GET request
const express = require("express");
const router = express.Router();
const pool = require("./db");
router.get("/", async (req, res, next) => {
pool.connect((err, client, done) => {
if (err) throw err;
client.query("SELECT * FROM pledges", (err, ress) => {
done();
if (err) {
console.log(err.stack);
} else {
console.log(ress.rows[0]);
res.json(ress.rows.reverse());
}
});
});
});
However, if I change it to a POST request, I get the correct query and returns the whole table. What am I doing wrong?
const express = require("express");
const router = express.Router();
const pool = require("./db");
router.post("/", async (req, res, next) => {
pool.connect((err, client, done) => {
if (err) throw err;
client.query("SELECT * FROM pledges", (err, ress) => {
done();
if (err) {
console.log(err.stack);
} else {
console.log(ress.rows[0]);
res.json(ress.rows.reverse());
}
});
});
});
Here is my FETCH
useEffect(() => {
fetch("/pledges")
.then((response) => response.json())
.then((data) => {
console.log(data);
setPledges(data);
})
.catch((error) => {});
}, []);
Fetch with POST request
useEffect(() => {
fetch("/pledges", {
method: "POST",
})
.then((response) => response.json())
.then((data) => {
setPledges(data);
})
.catch((error) => {});
}, []);
Likely the server is returning something that is not JSON, something with a "<" in it, like XML or HTML. Try setting the content header appropriately.
fetch(url, {
method: "GET",
headers: {
"Content-Type": "application/json"
}
})

How to send a file from ReactJs to Flask using Axios

I am attempting to send a file from a ReactJs Frontend, using an axios call, to a flask Backend.
Here is my axios call:
const audio_file = new File(buffer, 'recording.mp3', {
type: blob.type,
lastModified: Date.now()
});
const blobURL = URL.createObjectURL(blob);
this.setState({blobURL, isRecording: false, recorded:true})
let options = {
method: 'POST',
url: flaskEndpoint + "audio/1",
file: audio_file,
crossOrigin:'*'
}
console.log(options)
axios(options)
.then(response => {
console.log(response)
})
.catch(error => {
console.log("Error in the axios call:" + error);
})
At the moment my flask method looks like this :
#app.route('/audio/<int:user_id>', methods=['POST'])
#cross_origin()
def make_audio(user_id):
print(request.files.get('recording.mp3'))
print(request.files)
return 0
Here is the console of the python app:
And here is the web console of the React App:
Am I making a mistake here?
Edit
Ok I tried the suggestion of converting the file to base64 and then sending the file the backend.
This is my new axios call.
let options = {
method: 'POST',
url: flaskEndpoint + "audio/1",
data: convertBlobToBase64(blob),
// file: audio_file,
crossOrigin:'*',
headers: {
'Content-Type': 'application/json'
},
json: true
}
console.log(options)
axios(options)
.then(response => {
console.log(response)
})
.catch(error => {
console.log("Error in the axios call:" + error);
})
});
Here is the convetBlobtoBase64 functions (borrowed from: https://gist.github.com/n1ru4l/dc99062577b746e0783410b1298ab897)
const convertBlobToBase64 = blob => new Promise((resolve, reject) => {
const reader = new FileReader;
reader.onerror = reject;
reader.onload = () => {
resolve(reader.result);
};
reader.readAsDataURL(blob);
});
And here is what is being sent to the backend:
I think this answers my question, although I will create another to work out how to access the data on the flask end.

Fetch request always returns network error

I almost finished creating React Native application, few days ago register action has stopped working.. I'm sending fetch request and it always returns network error altough there is 400 response and message that user exists, it stops there..
I'm destructuring the response and displays api response message instead of fetch network error but now it doesn't work. I'm doing the same for the login action and it works.
Could it be something with multipart/form-data ?
export const register = data => dispatch => {
dispatch(createUser());
const d = new FormData();
d.append("name", data.name);
d.append("email", data.email);
d.append("password", data.password);
d.append("avatar", data.avatar);
fetch(API_URL + "/register", {
method: "POST",
headers: {
"content-type": "multipart/form-data"
},
body:d
})
.then(response => response.json().then(user => ({ user, response })))
.then(({ user, response }) => {
if (!response.ok) {
console.log(response, user)
} else {
console.log(response, user)
}
})
.catch(err => {
throw err;
});
};
The api route works in Postman..
In this case, your using fetch which is Promise based incorrectly,
Try,
fetch(API_URL + "/register", {
method: "POST",
headers: { "content-type": "multipart/form-data" },
body:d
})
.then(response => {
console.log(response, response.json().user)
})
.catch(err => {
console.log(err)
});
Check the logs and see if it shows proper network response and debug from there.

Resources