I made a POST request to get a QRCode
Here is the data I get from the response. The preview of the response works fine only I don't know how to use this data to display it in a tag on my html page for example. Any ideas?
It finally works as : (in async function)
const response = await fetch(URL_FOR_QRCODE, //your own url
{
method: "POST", //because my endpoint is a post method
credentials: 'include' //because I use cookies (its a auth qr code)
});
this.QRCodeSRC = URL.createObjectURL(await response.blob());
Related
I am trying to make a post request from a form to an endpoint, the form works fine, and the db too. The main issue is that i am posting to this endpoind localhost:3001/professional with the body of the form as data
export const postPro = (data) => async () =>{
console.log(data)
axios({
method: 'post',
url: "http://localhost:3001/professional",
data: data
})
}
data itself is an object. This is what i get from the console after i press send:
console of backend returning options, I did the first 2 post with postman to see if it works the db, and indeed it does.
I am using Redux toolkits(first time i use it) and React Native
I try rewriting the post, like this:
axios.post("http://localhost:3001/professional", data)
then i try to console.log the data to see if reaches the axios.post and it does, i can see the log of the object data in the console.
Also i was thinking that has something to do with async await so i try to play with that a little, and it's the same result.
login.js file:
const form = document.getElementById('loginForm');
form.addEventListener('submit',async(e)=>{
e.preventDefault();
return await fetch(`localhost:8000/route`, {
method: "get",
headers: {
"Content-Type": "application/json",
},
});
}
app.js file:
app.get('/index',(req,res)=>{
res.render('route.ejs');
})
I only get the rendered html as a response but can't render it.I know that using form submission works.But can anyone plz tell me how to render the page without submitting form?Thank you in Advance.
The reason you get HTML as a response and not rendered because you use an AJAX call when using fetch. It doesn't instruct the browser what to do with that response.
You have few options.
Either when you get the response back you handle it in your callback like so:
return await fetch(`localhost:8000/route`, {
method: "get",
headers: {
"Content-Type": "application/json",
},
}).then(res=> {
let htmlText = await response.text();
document.getElementsByTagName('body')[0].innerHTML(bodyContent);
});
Or in fact if you just want to load a new page from your ejs template, set the window to the new location and browser will automatically render the response. Something like so in your login.js:
document.location.href = "/route_that_returns_html";
Note that since your question is generic you can take one of the above approach. However as your code suggests if you are trying to implement a login then the right way to do it is in following steps:
Let the form submit as usual ( not using ajax/fetch)
On server side using express, execute the login routine to authenticate the user.
If the authentication passes issue a res.redirect() to the authenticated page that renders using ejs or if fails, redirect back to login page with error.
Finally this DigitalOcean Article explains how to use ejs properly and is worth a read.
I am trying to download a file when a user clicks on a particular button. This file is an image which gets created when the said button is pressed. What I want is, it should automatically download the image on the client's device.
I am using Flask on the server code, and ideally, the send_file function of Flask should trigger this auto download as it adds the Content-Disposition header.
On the client side, I have a JS code which uses fetch API to send a POST request to the server with some data, which is used for generating the image which is to be downloaded.
This is the JS code:
function make_image(text){
const json={
text: text
};
const options={
method: "POST",
body: JSON.stringify(json),
headers:{
'Content-Type':'application/json',
}
};
fetch('/image',options)
.then(res=>{
res.json(); //Gives an error: Uncaught (in promise) SyntaxError: Unexpected token � in JSON at position 0
}).catch(err=>console.log(err));
}
And this is the Python code on the server:
#app.route('/image',methods=['POST'])
def generate_image():
cont = request.get_json()
t=cont['text']
print(cont['text'])
name = pic.create_image(t)
time.sleep(2)
return send_file(f"{name}.png",as_attachment=True,mimetype="image/png")
But nothing is happening. The image doesnt get downloaded. However,the image is getting created on the server and is not corrupt
How do I resolve this? And is there some other way to do what I am trying to do?
You can do the below
return send_from_directory(dir, file_name, as_attachment=True)
This will download the file on the user's machine.
Edit:
BTW, if you create an html form like below, you do not need javascript.
<form action='action here' method='post'>
<input type='submit'>
</form>
As #clockwatcher mentioned a different question, I used the download.js module to handle the download of the image.
So my JS code looks like this now:
function make_image(text){
const json={
text: text
};
const options={
method: "POST",
body: JSON.stringify(json),
headers:{
'Content-Type':'application/json',
}
};
fetch('/image',options)
.then(res=>{
return res.blob();
}).then(blob=>{
download(blob)
}).catch(err=>console.log(err));
}
And an addition to the script tag in the html:
<script src="https://cdnjs.cloudflare.com/ajax/libs/downloadjs/1.4.8/download.min.js"></script>
With no change in the Python server code.
It works now
I'm trying to upload a gif from the webcam feed to Giphy through their API and it returns status 400 - "Please supply a file upload or a 'source_image_url'". My function does this:
upload = new FormData();
upload.append("file", gif, "usergif.gif");
console.log(upload.get("file"));
fetch("https://upload.giphy.com/v1/gifs?file=" upload + "&api_key=" + apiKey, { method: "POST" })
.then(response => {
console.log(response.status);
return response.json;
}
)
The gif variable inside upload.append() has a value of recorder.getBlob() (I'm using the RecorderRTC API), I also tried to use as a source upload.file and even upload.get("file"), also used URL.createObjectUrl(gif) and changed file= for source_image_url= in the fetch request, even tried to send the gif variable without the use of FormData() but nothing worked.
Do you have a clue?
For those interested, the solution was that when using the POST method, you gotta specify a body header with the file to be uploaded
I am trying to send basic auth header to Paypal api but can not get the format right. I read somewhere that I have to Base64 encode the credentials but that does'nt worked well and no response is generated. Here is the request I would like to send to REST API
var options = {
url: 'https://api.sandbox.paypal.com/v1/oauth2/token',
method: 'POST',
headers: 'application/json',
auth: {
'user': 'XXXXXX',
'pass': 'YYYYYY'
}}
Sample request in curl which I wish to send in javascript
Paypal get access token api
under the heading POSTMAN
What will be correct structure to send this request?
I was missing the : thing now I can get the correct Base64 value and concatenate to authorization header and its working fine