Convert this CURL Command to Javascript fetch() - reactjs

I have a problem, I'm trying to access an API via javascript fetch().
In their documentation, they only have the curl guide
curl https://test.com/form/{form_id}/data \
-u apikey:'some-key'
Can you guys help me convert it to javascript fetch?
I tested the code below but the browser console says error 401 now I don't think I did put the apikey on the right location.
fetch(https://test.com/form/371489/data', {
method: 'GET',
headers: {
'Accept': 'application/json',
apikey : 'some-ley',
'Content-Type': 'application/json'
}
})
Thanks in advance. :)

I think what is failing there is the type of header you are sending in fetch.
The -u option in curl translates to the "authorization" header in fetch. So it would be something like this.
fetch(https://test.com/form/371489/data', {
method: 'GET',
headers: {
'Accept': 'application/json',
'authorization' : 'Basic apikey:some-key',
'Content-Type': 'application/json'
}
})
Although probably you would need to base64 encode the apikey:some-key portion before sending it.

Try this format:
fetch("https://test.com/form/{form_id}/data", {
headers: {
Authorization: "apikey ABCDEFGHIJK.."
}
})

Try these awesome online cURL converters!
Here is the output when you paste the cURL command and select the Javascript target:
fetch('https://test.com/form/371489/data', {
headers: {
'Authorization': 'Basic ' + btoa('apikey:some-key')
}
});

Related

Napster API Auth - BAD Request / Unauthorized

I am coding in Reactjs and trying to Auth/Outh into the Napster Web API, followed the information on this page: https://developer.napster.com/api/v2.2#authentication
A sample of my current code:
const API_KEY = 'OWIxMjhlY2MtOTA3Yi00NWJiLThiYTktODc3OTNiYTQ4MGU4';
const API_KEY_SECRET = 'OWIxMjhlY2MtOTA3Yi00NWJiLThiYTktODc3OTNiYTQ4MGU4';
url: 'https://api.napster.com/oauth/access_token',
method: 'post',
params: {
client_id: API_KEY,
client_secret: API_KEY_SECRET
},
headers: {
'Accept':'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Bearer ' + (new Buffer(API_KEY + ':' + API_KEY_SECRET).toString('base64'))
},
data: querystring.stringify({ grant_type: 'authorization_code' })
Response Payload:
{"code":"UnauthorizedError","message":"Authentication code not valid"}
{"code":"BadRequestError","message":"Invalid grant_type parameter"}
According to the documentation and sample below....
curl -v -X POST -d "client_id={api_key}&client_secret={api_secret}&response_type=code&grant_type=authorization_code&redirect_uri={redirect_uri}&code={temporary_code}" "https://api.napster.com/oauth/access_token"
...You don't need to send Authorization headers. It's a normal form post with all the parameters. So If you include the rest of the parameters along with client_id : API_KEY... it should do the trick.

What is the best way to enable CORS in React Application?

There are different ways to make a REST call in react-
e.g
axios.post('link', JSON.stringify(data1),
{
headers: {"content-type" : "application/json", "Access-Control-Allow-Origin" : "*"}})
.then(response => {
console.log("res:", response)
})
.catch(err =>{
console.log(err)
})
}
OR
fetch('http://localhost:8080/feedbacks/addfeedback', {
method: 'post',
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin' : '*'
},
body:body
What is the most effiecient way to enable CORS.
Is there any other way that I can do this either in frontend or backend?
It depends on what HTTP library you are using.
See What is difference between Axios and Fetch?.
I usually use Axios, next what i do is creating a global instance and configuring Axios once.
export const api = axios.create({
baseURL: '_URL_',
timeout: 1000,
withCredentials: false,
responseType: 'json',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*' // whatever you want
}
});
// You can add common headers later
api.defaults.headers.common['Authorization'] = `Bearer ${token}`;
Also i'm enabling CORS on my server side application.
Thanks to #henrik123 for good explanation:
The browser is going to see that some Javascript request has tried to initiate a request to a different domain, subdomain or port than what the browsers is currently at. If any of these things are different, the CORS kicks in. Doesn't matter if you use Axios, Fetch or any other other library

Can't send auth headers with axios

Can't send authorization header with rest API. Got 'OPTIONS' error with status 0. All headers and options are allowed on the server. Server is written on PHP.
Here is my request:
axios.post(`${API_URL}users/${23}/profile/main/update`,
{formData},{
headers:{ 'Content-Type':'multipart/form-data',
Authorization:`Bearer ${token}`}
})
It seems like it does not send the header when there is authorization. However, it works, if i delete authorization, and leave only content type
This should do the trick
axios({
method: 'POST',
url:`${API_URL}users/${23}/profile/main/update`,
headers: {
'Content-Type':'multipart/form-data',
'Authorization':`Bearer ${token}`},
data: formData
})
Refer docs for browser
Try to send as below:
var headers = {
'Content-Type': 'multipart/form-data',
'Authorization': `Bearer ${token}`
}
axios.post(`${API_URL}users/${23}/profile/main/update`,
{formData}, headers)
Try using Ajax call below:
import $ from 'jquery';
$.ajax({
url:`${API_URL}users/${23}/profile/main/update`,
processData: false,
contentType: false,
data : formData,
method : "POST",
headers: {
"Authorization": `Bearer ${token}`
}
});
I had this same issue, it is possible that you are not passing the sent auth header from your apache config to your php application.
you might need to set
WSGIPassAuthorization On
inside your virtualhost config.
Check this

React native - post raw text data

I want to send this type data in raw text format using react native. please help-
submit Qsubmit_form=1&form_noresubmit_code=1525265560&question=OKKKK NEW APPP&submit=
You can use fetch API for both GET and POST requests. Example of POST request:
fetch('https://mywebsite.com/endpoint/', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
firstParam: 'yourValue',
secondParam: 'yourOtherValue',
}),
});
You can check out official docs for networking here

react fetch header not set

I am facing a problem. And the solutions that are accepted by the others, those don't work for me./
I have:
return await fetch(url, {
method: httpMethod,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'x-test':'try me',
},
body: JSON.stringify(bodyObject)
});
But, it seems like no header is set at all.
Cors-header is set, adding mode:'cors' makes no difference.
Am I missing something?
the request:
Accept is empty and Content-Type nor x-test are nowhere to be found.
..
Edit
..
If i need to create new question, do tell me.
New request
So I see that the header is set - thanks to liminal18!-. However, now i want to authorize to an AD.
so now I got:
async callUrl(url, httpMethod, bodyObject) {
try {
var requestObj = {
method: httpMethod,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'x-test':'try me',
'Authorization': 'Basic Uk11bGxlc....'
}
};
if (bodyObject !== undefined){
requestObj.body = JSON.stringify(bodyObject);
}
return await fetch(url, requestObj);
} catch(error){
console.error(error);
}
}
But still get an 401.
I know this is not the clean solution for logging in, but just testing..
Are you sure the request you captured is the correct request?
if you're using CORS there is an OPTIONS post to get the cors allowed methods before react will post/put which might be what you are looking at and not the actual post or put you intended. Where are the CORS headers set?

Resources