Can't post videos to Tiktok using the Web Video Kit API - javascript

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.

Related

concatenation of request url to web archive's base url when using fetch api

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?

Download and save MJPEG with http command (Javascript)

I'm using a hikvision IP camera that streams 30 MJPEG images per second to a certain http url and Javascript Reactjs with nodejs and express as backend.
Also hikvision provides a url to snap the camera image when you open the link.
Example link:
http://192.168.0.109/ISAPI/Streaming/channels/1/picture
I want to download that image and store it as a local file on my computer, I know how to store it but I haven't been able to download the image programatically.
I followed the next guide to get those API endpoints (stream and snapshot):
HIKVISION TUTORIAL
My question is, how do I fetch or download that image ?
I have tried with fetch without success.
Not sure but as long as I understand it requires a basic digest authorization and I haven't find how to fetch with digest auth. If I open the link directly on my browser, a pop up prompts and ask me for my username and password.
Everytime I try to fetch the response is :
GET http://192.168.0.109/ISAPI/Streaming/channels/1/picture net::ERR_ABORTED 401 (Unauthorized)
There is also some parameters to this API command on documentation that includes a json format that I have tried without success:
Also, as you can see on HIKVISION TUTORIAL there is an url to get the stream, I'm able to reproduce that MJPEG stream on front-end with the next code with no issues:
<img
width={"90%"}
height={"60%"}
alt="stream"
src={"http://192.168.0.109/ISAPI/Streaming/channels/102/httpPreview"}
id="cam1"
/>
net::ERR_ABORTED 401 (Unauthorized)
Based on the error you presented, I suspect that you have set a username/password.
The documentation (that you linked to in your question) explains that if you have set a username/password, then you need to use Basic auth:
http://<username>:<password>#<IP address of IPC>:<HTTP
port>/ISAPI/Streaming/channels/1/picture
So, if the local IP address that you're using is 192.168.0.109, then the URL format would be:
http://<username>:<password>#192.168.0.109/ISAPI/Streaming/channels/1/picture
and <username> and <password> would be your actual username and password.
Note that this URL format is deprecated in many environments. You can send the auth data in the request headers instead:
function setBasicAuthHeader (headers, username, password) {
// In Node:
const encoded = Buffer.from(`${username}:${password}`).toString('base64');
// In a browser/deno:
// const encoded = window.btoa(`${username}:${password}`);
headers.set('Authorization', `Basic ${encoded}`);
}
const username = 'me';
const password = 'secret';
const headers = new Headers();
setBasicAuthHeader(headers, username, password));
// Use headers in your request...

Failing to fetch my local API running in localhost (Amazon Cloud 9)

I have a simple flask server that returns a JSON (flask automatically do that when you return a python dict) when it receives a GET request to / endpoint.
It's running on my 5000 port:
I know it's running and reachable as I managed to request to it, and receive a valid response, using curl, twice:
Both requests are logged into the server logs as well, on second print.
I'm trying to fetch to my server from a html/js script as:
const URL = "http://127.0.0.1:5000/"
fetch( URL )
.then(response=>response.json())
.then(json=>console.log(json))
or
const URL = "http://localhost:5000/"
fetch( URL )
.then(response=>response.json())
.then(json=>console.log(json))
But I get the same error twice:
1: GET http://localhost:5000/ net::ERR_CONNECTION_REFUSED
2: Uncaught (in promise) TypeError: Failed to fetch
I know the code itself works because I managed to fetch Githubs API:
const URL = "https://api.github.com/users/nluizsoliveira"
fetch( URL )
.then(response=>response.json())
.then(json=>console.log(json))
I'm not sure why I can't fetch to my localhost. I think it has something to do with how cloud9 deals with ports. When removing http://localhost from the url:
const URL = ":5000"
fetch( URL )
.then(response=>response.json())
.then(json=>console.log(json))
the snippet also fails, but it seems that the request is somehow appending the url to my C9 url.
Have someone faced that situation before?
Thanks a lot in advance!
EDIT:
Just to clarify, i'm not running that js/html (directly) on my browser tab. I'm running it on the C9's built in browser, which is available through "preview running application":
With AWS Cloud 9 Preview, AWS gives you a private link like https://12a34567b8cd9012345ef67abcd890e1.vfs.cloud9.us-east-2.amazonaws.com which gives you access to your application. To get that link click preview application and copy it from the browser tab.
Use that link in your code instead of localhost. AWS Documentation:Preview a running application.

Trouble finding Ocp-Apim-Subscription-Key for Azure Bing News

I am trying to create a successful request using Azure's Bing News API. The below screenshot from the docs says that the Ocp-Apim-Subscription-Key is a required header. https://learn.microsoft.com/en-us/rest/api/cognitiveservices-bingsearch/bing-news-api-v7-reference
I've made an account and according to this post Issue in accessing Bing Custom Web Search API v7 the key is found in the Bing Resource -> Keys & Endpoints:
I've tried both keys and neither work. I receive error code 401 Access denied due to Invalid subscription key or wrong API endpoint. I noticed that the endpoint featured in this picture is different from the endpoints listed in the bing new docs. I tried the endpoint listed in the picture (just to see) and I got a 404 error.
Another thread says to go to the API Management on the Azure portal.
https://learn.microsoft.com/en-us/answers/questions/62385/please-help-me-to-find-the-process-to-get-ampampam.html
Upon navigating to API Management menu it read "No API Management services to display". I can "Create API Management" but the subsequent forms asks for information that seems atypical to gain access to an API. Is this really where the key is created or am I doing something else wrong? Thank you.
Here is my code. I tried on Postman and ran into the same error.
import fetch from 'node-fetch';
function testFetch(){
let response = fetch("https://api.cognitive.microsoft.com/bing/v7.0/news/trendingtopics", {
headers: {
"Ocp-Apim-Subscription-Key": <redacted-key>,
'Accept': 'application/json',
'Content-Type': 'application/json'
}
}).then(async response => {
try {
const data = await response.json()
console.log('response data?', data)
} catch(error) {
console.log('Error happened here!')
console.error(error)
}
})
}
testFetch()
Please use the following endpoint BING_HOST = "https://api.bing.microsoft.com/v7.0/news/search" and find the below snapshot for the same.
Please follow the below documentation for bing news search.
https://learn.microsoft.com/en-us/bing/search-apis/bing-news-search/overview

xlsx file corrupted while downloading with the file-saver npm package

I am having a problem in downloading a xlsx file. My excel file is generated with js-xlsx. I have to add some authorization headers to verify the incoming requests on the server. For this reason, I can not just simply open the link in a new window from my client-side. For testing purpose, I try to download the file by directly hitting the browser link of my API endpoint (of course by removing the authorization middleware temporarily). The browser downloads the file without any problem or corruption. Unfortunately, this is not the case with the client-side download functionality while using filesaver.js through axios get request.
My snippet from the backend code where I am sending the response is:
//..... Some code for writing the workBook
const workBookOutput = xlsx.write(workBook, {
bookType: 'xlsx',
type: 'buffer'
});
const xlsxFileBuffer = Buffer.from(workBookOutput);
// res is express HTTP response object
res.set('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
res.set('Content-Disposition', 'attachment; filename=excel-export.xlsx');
res.status(200).send(xlsxFileBuffer);
The part of my client-side code is:
const headers = {
'Content-Type': 'application/json',
Accept: 'application/json'
};
// here I add some real jwt token in my code, not the dummy that I have below
headers.authorization = `bearer asklndashduwkhd2oo832uejh32oihjdoasincas`;
const options = {
'get',
'https://myURLToAPi/api',
headers,
responseType: 'arraybuffer'
}
const response = await axios(options);
//fileSaver is required above in file
fileSaver.saveAs(
new Blob([response.data], {
type:
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
}),
'excel.xlsx'
);
I still only get the corrupted file. I have tried multiple options on server and client-side both, nevertheless, the downloaded file always comes as corrupted. I have tried not making another Buffer.from after getting my workbookOutput still nothing has changed. Can someone help me in this regard? Am I missing something?
This is the picture of what I get for corrupt download if I try to open it.
I had a similar issue - I was generating Excel in Django, getting bytes then querying it using Axios. The Excel produced with FileSaver was corrupted, and, just like #Seeker mentioned, it was twice the size.
However I could get a normal file when testing in Postman. What solved my problem was setting
responseType: 'blob'
in axios options.

Categories

Resources