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

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

Related

Post call not placing headers in call. Axios

I'm trying to do an Api Call, this is the code I'm using
axios.get("url", userData, {
headers: {
Authorization: "test"
}
}).then((response) => console.log(response, 'users/me'))
.catch(err => console.log(err))
Its showing me the same error everytime
401 (Unauthorized)
And on the network on chrome dev tools, the Authorization is not appearing at all
Thanks a lot.
The Authorization reqest header has the following general scheme:
Authorization: <auth-scheme> <authorization-parameters>
Let us assume that your user id is john.smith and your password is password (don't do that).
Using the Basic authorization scheme, you take your user ID and password and join them with a colon:
john.smith:password
and then base-64 encyrpt that to get
am9obi5zbWl0aDpwYXNzd29yZA==
The Authorization header you need to pass then is
Authorization: Basic am9obi5zbWl0aDpwYXNzd29yZA==
Different schemes, of course, require different things in the header value.
Your 401 Unauthorized response status should have a WWW-Authenticate response header containing a list of 1 or more challenges telling you what authentication scheme(s) you may use.
Install Postman and fiddle with your API call until you get it working.
You can then export the API call as any of a number of different flavors of client-side code, Node.js - Axios being one of them.

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

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.

Request to b2c login is blocked by CORS policy

I'm developing a web application, where the user is given a challenge from the web app that contains a URL to another website, where he's asked to sign-up.
The sign-up page is made using the sign-up flow in Azure AD B2C.
The response sent from my ASP.NET Core API looks like this:
var redirectUrl = Url.Action(nameof(SignupController.Return), "Signup");
var properties = new AuthenticationProperties { RedirectUri = redirectUrl };
properties.Items[AzureAdB2COptions.PolicyAuthenticationProperty] = AzureAdB2COptions.SignUpPolicyId;
return Challenge(properties, OpenIdConnectDefaults.AuthenticationScheme);
The challenge is requested using Fetch API in Javascript, which looks like this:
fetch(`/api/invitations/${invitationId}`, {
method: 'PUT',
mode: 'cors'
}).then(response => {
// HTTP 301 response
if (response.redirected) {
console.log(response.url);
window.location.href(response.url);
}
})
.catch(function (err) {
console.log(err);
});
However I keep getting this error:
As far as I understand this is a server problem, but I suppose its on b2clogin? I can't really see how I'm supposed to update the CORS policy. I can easily access the fetch URL as shown above by clicking on it, but the javascript code itself cannot redirect to it. I'm sure it's just a simple fix. I hope someone will help.
I am not sure what you are trying to achieve here because of limited context. But, to fix this error, run below Azure CLI command in your Local:
az webapp cors add --resource-group myResourceGroup --name api-name --allowed-origins 'http://localhost:44315'
Check out more about CORS policies in App service here.

How do I fix CORS issue in Fetch API

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

Firebase auth with Facebook OAuth credential (from Google Extension)

I am just having fun with the new Firebase, but I'm struggling with auth system.
Because I'm trying to login user from options page of google extension, so I can't use signInWithPopup or Redirect method due (some) security reasons.
So I figure out possible solution. From options page I redirect user to my another page, where he can easily login with Firebase (by Facebook provider) - everything is OK - user obtain OAuth FB token and this page send message to extension to cache this token.
There lies the problem.
I have code like this:
firebase.initializeApp(FIREBASE_CONFIG);
var credential = new firebase.auth.FacebookAuthProvider.credential(token);
firebase.auth().signInWithCredential(credential)
.then((data) => {
console.log(data);
})
.catch((err) => {
console.error(err.code);
})
This fire up POST request to https://www.googleapis.com/identitytoolkit/v3/relyingparty/ and in response I can clearly see the error:
message:"INVALID_REQUEST_URI"
This request is fired with requestURI payload, which is in mine situation:
chrome-extension://kefhjfjilmodblnpnekjleceapohasdf/options.html
When I tried to fire this request from terminal with CURL and I faked the requestURI with 'http://localhost' everything is OK and I got correct data.
Do you have any ideas, how can I achieve proper behavior?
Thanks a lot.
P.S: I'm using Firebase.js 3.0.5-rc.2

Categories

Resources