I am requesting a response from Spotify API. All I need to know is how to get this python script statement into js. What should I use in java that is like requests in python
query = "https://api.spotify.com/v1/playlists/{}/tracks?uris=.
{}".format(created_playlist, tracks);
response = requests.post(query, {"headers": {"Content-Type": "application/json", "Authorization": "Bearer {}".format(token3)}})
For Javascript, ES6+, use the native fetch API to perform REST HTTP requests,
alternative is the npm axios library, check its documentation
you can use the fetch API its a promise based function different from python requests module
fetch('http://example.com/movies.json')
.then(response => response.json())
.then(data => console.log(data));
here are the docs
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
Related
I want to run some script from the browser console for external sites that extracts the dom tree with some format, I did it right but when I wanted to write the result in my file system. this was not allowed due to security issues, so I wrote a backend script using Node.JS that writes into the file system using a post request from the console an reading from the file system while sending a get request on another endpoint.
this is a part of the code I run on the console in which I'm using the fetch API to send my data to the backend (dict)
let dict = generateDictionary(root);
const url = new URL("http://localhost:5000/write");
fetch(url, {
method: "POST",
body: JSON.stringify({ data: JSON.stringify(dict) }),
headers: {
"Content-Type": "application/json"
},
})
.then((response) => console.log(response))
.then((data) => console.log(data));
for most of different sites it works well like that
and this is a snippet from the dom tree after serialization
the problem appears when I use https://web.archive.org/ historical pages to send the same request like https://web.archive.org/web/20220201010705/https://www.reference.com/.
here as it appears on the snapshot it appends the localhost URL to the web archive's URL. I tried to modify different http headers to solve the problem but all of my trials have failed. what can I do to avoid this concatenation?
I am trying to upload a video to Tiktok using this endpoint:
https://open-api.tiktok.com/share/video/upload/
Following the official docs:
https://developers.tiktok.com/doc/web-video-kit-with-web
(After successfully authenticating with Tiktok and getting an access token using the Login Kit API).
I am getting a response that suggests success (with error_code=0 and a non-empty share_id), however nothing gets uploaded and my Tiktok app's callback url does not seem to be getting triggered with any status update.
I've tried hitting the API from several different environments - a Node.js runtime (using Axios), a cURL request from 2 different machines (all getting the result described above) and also from my frontend code using Fetch (this one got me a CORS error). Code snippets below.
Will appreciate any help since I'm out of ideas as for what to try next. Also if there are any other docs or online resources besides the one I linked to that might be helpful, any links to such will be great.
Note: I made sure my test videos are satisfying the constraints mentioned in the docs.
My Node.js code:
const url = `https://open-api.tiktok.com/share/video/upload?open_id=${openId}&access_token=${accessToken}`;
const data = new FormData();
data.append('video', fs.createReadStream(path.join(os.tmpdir(), 'test.mp4')));
await axios.post(url, data, {
headers: data.getHeaders()
});
cURL request:
curl --location --request POST 'https://open-api.tiktok.com/share/video/upload?open_id=<open_id>&access_token=<access_token>' --form 'video=#"/path/to/video.mp4"'
Response payload (for both cURL and Node.JS requests):
{"data":{"err_code":0,"error_code":0,"share_id":"video.7031619168818448385.CGdXCmaC"},"extra":{"error_detail":"","logid":"2021111721133201024513311411A971D3"}}
Frontend code (Fetch, getting a 307 response with the same Tiktok URL (/share/video/upload...) in the Location header - resulting in CORS error):
const formData = new FormData();
formData.append('video', selectedFile);
const requestOptions = {
method: 'POST',
body: formData,
redirect: 'follow'
};
const URL = `https://open-api.tiktok.com/share/video/upload?access_token=${accessToken}&open_id=${openId}`;
fetch(URL, requestOptions)
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.log('error', error));
You need to download the TikTok app then publish the video uploaded by your API.
The user who triggered the video upload should receive a notification
on TikTok App after the video uploaded successfully and the user can
publish the video on the app.
In case you get "Something went wrong, try again later". It is probably your region issue. You will need to try a vpn and try again.
I have this code
fetch('http://example.com/movies.json')
.then(response => response.json())
.then(data => console.log(data));
Is using Fetch API for a request like in the code above considered as an AJAX request?
I a request considered an AJAX request only if we use the XMLHttpRequest object ?
Yes, There are several ways to send Asynchronous requests like jQuery, axios, Fetch API or XMLhttprequest.
fetch is an ajax request.
but fetch is a simple api and have not, so I recommended fatcher
fatcher is a lightweight HTTP request library based on fetch, allows us to use native fetch for web requests in a browser and NodeJS environment.
It is wrapped using the native fetch, we require that browsers or NodeJS support fetch when we use it.
Fetch support is already pretty good in modern browsers, so we don't have to worry about FETCH compatibility
In NodeJS, fetch already has some support starting with '18.0.0'
Fatcher aims to embrace the fetch of the standard library and at the same time provide some functions that cannot be provided in fetch, as well as make the function better expand and reuse.
import { fatcher, isFatcherError } from 'fatcher';
fatcher({
url: '/',
})
.then(result => {
// Response
const { data, status } = result;
})
.catch(err => {
// Catch Fatcher Error
if (isFatcherError(err)) {
// Request successfully. But response status code is not 2xx.
console.error(err.toJSON());
return;
}
// This is other errors.
});
Issue
I started a new VueJS project using the Vue CLI. I'm using fetch to POST login info to a remote DEV server. When I call this method on my local environment it processes this call as a GET then a POST then a OPTIONS then a GET.
This is what the network panel from Chrome shows after I run the POST request.
When it hits the api server it is being processes as a GET request which is returns a 405 as it is a POST not a GET.
Question
Why is it bouncing between two 301s and then converting the call to a GET request.
Tools
I'm using VueJS 2 CLI, Webpack, and Babel
Note: I replaced the real api url and server with a fake one
JavaScript Fetch method
authenticate (username, password) {
const url = '/api/login/authenticate/'
return fetch(url, {
method: 'POST',
body: JSON.stringify({ username, password }),
headers: new Headers({
'Content-Type': 'application/json'
})
}).then(res => res.json());
}
Webpack API Proxy Setup
proxyTable: {
"/api": "http://www.myDevServer.net"
}
I got it to work when I changed the Webpack API Proxy Setup to match this pattern. I have not yet found docs on changeOrigin but it seems self explanatory.
Corrected Webpack API Proxy Setup
proxyTable: {
"/api": {
target: "http://www.myDevServer.net",
changeOrigin: true
}
}
What I'm guessing happened was I called a proxy that changed origin. As the proxy server didn't allow this so it returned a 301. As the server was not there it didn't allow POST requests. Then the proxy tried to see what options were available, so it sent an OPTIONS call. It saw GET was allowed and called it. The GET was trying to process under my POST call and it failed as the format was wrong which returned a 405
I'm building a front-end only basic Weather App using reactjs. For API requests I'm using Fetch API.
In my app, I'm getting the current location from a simple API I found
and it gives the location as a JSON object. But when I request it through Fetch API, I'm getting this error.
Failed to load http://ip-api.com/json: Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers in preflight response.
So I searched through and found multiple solutions to fix this.
Enabling CORS in Chrome solves the error but when I deploy the app on heroku, how can I access it through a mobile device without running into the same CORS issue.
I found an proxy API which enables the CORS requests. But as this is a location request, this gives me the location of the proxy server. So it's not a solution.
I've gone through this Stackoverflow question and added the headers to the header in my http request but it doesn't solve the problem. (Still it gives the same error).
So how can I solve the issue permanently ? What's the best solution I can use to solve the CORS issue for http requests in Fetch API ?
if you are making a post, put or patch request, you have to stringify your data with body: JSON.stringify(data)
fetch(URL,
{
method: "POST",
body: JSON.stringify(data),
mode: 'cors',
headers: {
'Content-Type': 'application/json',
}
}
).then(response => response.json())
.then(data => {
....
})
.catch((err) => {
....
})
});
To the countless future visitors:
If my original answer doesn't help you, you may have been looking for:
Trying to use fetch and pass in mode: no-cors
What is an opaque response, and what purpose does it serve?
Regarding the issue faced by the OP...
That API appears to be permissive, responding with Access-Control-Allow-Origin:*
I haven't figured out what is causing your problem, but I don't think it is simply the fetch API.
This worked fine for me in both Firefox and Chrome...
fetch('http://ip-api.com/json')
.then( response => response.json() )
.then( data => console.log(data) )
You should use the proxy solution, but pass it the IP of the client instead of the proxy. Here is an example URL format for the API you specified, using the IP of WikiMedia:
http://ip-api.com/json/208.80.152.201