request json from html using JavaScript - javascript

I am unable to request JSON from HTML using request.
I am using the request package from npm.
<!DOCTYPE html>
<html lang="en">
<head>
<title>MySite!</title>
</head>
<body>
<h2>
its ya boi
</h2>
<button onclick=ree>workkkkk</button>
<script>
const request = require('request')
function ree() {
request('https://api-quiz.hype.space/shows/now',(error,response,body) => { //requests data from the hq trivia api
//bodys = JSON.parse(body)
//document.getElementById("para").innerHTML = (bodys.nextShowPrize)
//console.log(`Next game: ${body.nextShowTime}`)
alert(body)
})}
</script>
</body>
</html>

You could use fetch.
fetch('https://api-quiz.hype.space/shows/now')
.then(res => res.json())
.then(console.log)

Related

Trying to fetch and display image from api using javascript?

I am currently building a football website using LiveScore API to fetch data. Needless to say, I am actually learning API fetch using this project. This api fetch current day's fixture. I tried to get the two teams T1 and T2 with their name playing against each other in my HTML file. I got the output below.
Output and api
There are overall 81 arrays, and I want to display logo of the team which is in T1 and T2 array in Img section just before the team name. But only a placeholder is displaying. What am I doing wrong?
I wrote some HTML and JS to fetch the data.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Football Live Today</title>
</head>
<body>
<div>
<h2>Football Live Today</h2>
<h3>Today's Fixtures</h3>
<ul>
<li id="fixtures"></li>
</ul>
</div>
<script src="popup.js"></script>
</body>
</html>
JS
async function fetchData() {
const options = {
method: 'GET',
headers: {
'X-RapidAPI-Key': '********',
'X-RapidAPI-Host': 'livescore6.p.rapidapi.com'
}
};
const res = await fetch('https://livescore6.p.rapidapi.com/matches/v2/list-by-date?Category=soccer&Date=20231801&Timezone=-7', options)
const record = await res.json()
console.log('record', record)
const indices = [0, 1, 4, 49, 50];
const filteredStages = record.Stages.filter((stage, index) => indices.includes(index));
document.getElementById("fixtures").innerHTML = filteredStages.map(item => `
<li>${item.Cnm} | ${item.Snm} | <img src="('${item.Events[0].T1[0].Img}">
${item.Events[0].T1[0].Nm} Vs <img src="${item.Events[0].T2[0].Img}">
${item.Events[0].T2[0].Nm}</li>`);
}
fetchData();

FastAPI - Uploading multiple files using Axios raises Bad Request error

Client code:
!<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
</head>
<form id="uploadForm" role="form" method="post" enctype=multipart/form-data>
<input type="file" id="file" name="file" multiple>
<input type=button value=Upload onclick="uploadFile()">
</form>
<script type="text/javascript">
function uploadFile() {
var formData = new FormData();
var imagefile = document.querySelector('#file');
formData.append("images", imagefile.files);
axios.post('http://127.0.0.1:8000/upload', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
})
}
</script>
</body>
</html>
Server code:
from fastapi import FastAPI, File, UploadFile, FastAPI
from typing import Optional, List
from fastapi.responses import FileResponse, HTMLResponse
from fastapi.staticfiles import StaticFiles
from fastapi.middleware.cors import CORSMiddleware
...
def save_file(filename, data):
with open(filename, 'wb') as f:
f.write(data)
print('file saved')
#app.post("/upload")
async def upload(files: List[UploadFile] = File(...)):
print(files)
for file in files:
contents = await file.read()
save_file(file.filename, contents)
print('file received')
return {"Uploaded Filenames": [file.filename for file in files]}
I get the following error:
←[32mINFO←[0m: 127.0.0.1:10406 - "←[1mPOST /upload HTTP/1.1←[0m" ←[31m400 Bad Request←[0m
I have tried to upload a single file via form action and all works fine, but I need to upload two files.
First, when uploading files or form data, one should use the same form key defined in their endpoint/route. In your case, that is files. Hence, on client side you should use that key instead of images.
Second, the way to upload multiple files is to loop through the array of files (i.e., imagefile.files in your code) and add each file to the FormData object.
Third, the error seems to occur due to some bug/changes in the 0.27.1 version of Axios. Here is a recent related issue on GitHub. Using the latest version, i.e., 0.27.2, from cdnjs here resolves the issue.
Alternatively, you could use Fetch API, similar to this answer (you can add the list of files in the same way as shown in the Axios example below). In Fetch API, when uploading files to the server, you should not explicitly set the Content-Type header on the request, as explained here.
Working Example (using Axios)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Upload Files</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.27.2/axios.min.js"></script>
</head>
<body>
<input type="file" id="fileInput" multiple><br>
<input type="button" value="Upload" onclick="uploadFile()">
<script type="text/javascript">
function uploadFile() {
var fileInput = document.querySelector('#fileInput');
if (fileInput.files[0]) {
var formData = new FormData();
for (const file of fileInput.files)
formData.append('files', file);
axios({
method: 'post',
url: '/upload',
data: formData,
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data'
}
})
.then(response => {
console.log(response);
})
.catch(error => {
console.error(error);
});
}
}
</script>
</body>
</html>
Starting from Axios v 0.27.2 you can do this easily:
axios
.postForm("https://httpbin.org/post", document.querySelector("#fileInput").files)
All the files will be submitted with files[] key.
More verbose example:
axios.postForm("https://httpbin.org/post", {
"myField": "foo"
"myJson{}": {x:1, y: 'bar'},
"files[]": document.querySelector("#fileInput").files
})

So i'm trying to get my axios response in an array and I don't know how to do it

So i'm trying to get my axios response from a spring boot page into a vuejs array And i don't know why but apperently i can't use split here. I'm pretty new to vue.js so please go easy on me.
Vue.js code:
// JavaScript source code
new Vue({
el: '#app',
data() {
return {
urls: [],
url: ""
}
},
mounted() {
axios
.get("http://localhost:91/all/URL")
.then(response => (this.url = response.data, this.urls = this.url.split(",")))
}
})
HTML:
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="https://cdn.jsdelivr.net/npm/vue#2.6.12/dist/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<meta charset="utf-8" />
<title>Home</title>
</head>
<body>
<div id="app">
<ul v-for="url in urls">
<li> {{ url }} </li>
</ul>
</div>
<script src="Script.js"></script>
</body>
</html>
console throws following error:
Script.js:14 Uncaught (in promise) TypeError: this.urlfound.split is not a function
at Script.js:14
There is conflict between variable names, in template you have url from v-for and also in data the same url is defined.

How to upload a file from Vue frontend to FastAPI backend

Vuejs Code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script src="https://unpkg.com/vue"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<div id="file-upload-list" class="container">
<div class="large-12 medium-12 small-12 cell">
<label>File
<input type="file" id="file" ref="file" v-on:change="handleFileUpload()"/>
</label>
<button v-on:click="submitFile()">Submit</button>
</div>
</div>
<script>
var fileList = new Vue({
data(){
return {
file: ''
}
},
el: "#file-upload-list",
methods: {
/*
Submits the file to the server
*/
submitFile(){
/*
Initialize the form data
*/
let formData = new FormData();
/*
Add the form data we need to submit
*/
formData.append('file', this.file);
console.log(this.file);
var baseURL="http://127.0.0.1:8000"
/*
Make the request to the POST /single-file URL
*/
axios.post( baseURL+'/uploadfiles',
// formData,
{
headers: {
'Content-Type': 'multipart/form-data'
},
file:this.file
}
).then(function(){
console.log('SUCCESS!!');
})
.catch(function(){
console.log('FAILURE!!');
});
console.log(formData);
},
/*
Handles a change on the file upload
*/
handleFileUpload(){
this.file = this.$refs.file.files[0];
}
}
});
</script>
</body>
</html>
FastAPI code
#app.post("/uploadfiles/")
async def create_upload_files(files: List[UploadFile] = File(...)):
result=""
for file in files:
fpath = os.path.join(
STORAGE_PATH, f'{file.filename}'
)
async with aiofiles.open(fpath, 'wb') as f:
content = await file.read()
await f.write(content)
return {"message": "success"}
I am trying to upload a pdf file from vuejs to fastAPI. where pdf file will be saved in a particular location in fastAPI code mentioned. I have tested the fastapi code in postman and it works good and I also enabled cross-origin. I am new to vuejs and I don't know how to do form action functionality. Mainly I need to know HTTPFile transaction is happening in the vuejs

Returning HTML with Azure Serverless Function req.body

I've got some TIF files in Azure Blob Storage. I'd like to display them in the browser via a link embedded in a spreadsheet. The simplest way to do this should be to take the file code as a request parameter and return the properly formatted HTML, right?
So right now I've got it returning a req.body with some HTML. Unfortunately, the HTML just shows up as a string in the browser. How do I make it render as HTML with minimal rigamarole?
Here's my code:
if (req.query.blob) {
let blob = req.query.blob;
context.res = {
// status: 200, /* Defaults to 200 */
body: `<object width=200 height=200
data="<baseaddress>/${blob}.tif" type="image/tiff">
<param name="src" value="<baseaddress>/${blob}.tif">
<param name="negative" value="yes">
</object>`
};
}
You need to set the headers to specify the content type to HTML and the response must be a full valid HTML page (with the <html> tag and the rest).
Example:
module.exports.hello = (event, context, callback) => {
const html = `
<!doctype html>
<html>
<head>
<title>The Page Title</title>
</head>
<body>
<h1>Hello</h1>
</body>
</html>`;
const response = {
statusCode: 200,
headers: {
'Content-Type': 'text/html'
},
body: html
};
callback(null, response);
};

Categories

Resources