I'am currently trying to get the status of a GitLab job with Javascript on GitLab Pages.
I have tried the following but I always receive an error 404 not found.
fetch('https://gitlab.devops.telekom.de/api/v4/projects/165107/jobs', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'PRIVATE-TOKEN': 'TOKEN'
},
body: JSON.stringify({ "id": 78912 })
}).then(response => response.json()).then(response => console.log(JSON.stringify(response)));
Related
I'm new to programming and I'm currently working on a small project.
I'm trying to implement some authorization using JWT.
I've watched a few videos online and found that most people have the "Bearer" + access token in their headers.
I've gone through a few posts and I found that I needed to add the authorization "Bearer" myself but I'm not quite sure how to get there.
Can I please get some help?
Here are some of my code
Login
if(response){
if(await bcrypt.compare(loginPW, response.password)){
const accessToken = jwt.sign({
email: response.email
},jwtSecret)
res.json({status: 'ok', accessToken: accessToken})
}else{
return res.json({status: 'error', error:'Invalid Credentials'})
}
}
Post request
const result = await fetch('/',{
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
loginEmail, loginPassword, reqType
})
}).then((res) => res.json());
just add Authorization header with your token to request
const result = await fetch('/',{
method: 'POST',
headers: {
'Content-Type': 'application/json'
'Authorization': `Bearer ${accessToken}`
},
body: JSON.stringify({
loginEmail, loginPassword, reqType
})
}).then((res) => res.json());
one possible way is ....on your Post requst result you can store the accessToken in localStorage
const result = await fetch('/',{
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
loginEmail, loginPassword, reqType
})
}).then((res) => res.json()).then(({accessToken})=>{
localStorage.setItem('accessToken', accessToken)
});
then retrieve it in all of your requests
const anotherRequst = await fetch('/anything',{
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${localStorage.getItem('accessToken')}` // get it from localStorage
},
body: ... /// anything
}).then((res) => res.json());
that's the simplest way
... for more advanced techniques, try to use Axios
and you can simply set the default authorization header in all your requsts
axios.defaults.authorization = localStorage.getItem('accessToken')
then any request you make will have the accessToken in its header
Axios.post(....)
Axios.get(...)
....
You can add 'Authorization' headers within your request just like this
const result = await fetch('/',{
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${accessToken}`
},
body: JSON.stringify({
loginEmail, loginPassword, reqType
})
}).then((res) => res.json());
Or if you're dealing with a big project and you have to send the token with every request then you can use Axios which allows you to add common headers with every request using only one line
axios.defaults.headers.common['Authorization'] = `Bearer ${accessToken}`;
Docs: https://www.npmjs.com/package/axios
I’ve been trying to authenticate with the Walmart Marketplace API for both sandbox and production but have so far been unsuccessful. In all cases when I ping a request to the “Token API” (https://sandbox.walmartapis.com/v3/token) I get back the the following error code: “SYSTEM_ERROR.GMP_GATEWAY_API”. I’ve tried to authenticate with both JSON and XML but no luck.
Here is my request with JSON:
{
url: 'https://sandbox.walmartapis.com/v3/token',
data: { grant_type: 'client_credentials' },
options: {
headers: {
Authorization: 'Basic <base64String>=',
Accept: 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
'WM_SVC.NAME': 'Walmart Marketplace',
'WM_QOS.CORRELATION_ID': '1bca34cd-478f-4022-8c13-9b88293f56b2',
'WM_SVC.VERSION': '1.0.0'
}
},
method: 'post'
}
Here is the error I'm getting with JSON:
error: [
{
code: 'SYSTEM_ERROR.GMP_GATEWAY_API',
description: 'Illegal character in query at index 172: http://partner-read-srvc-app.prod2.partnerreadservice1.catdev.prod.walmart.com/partner-read-srvc-app/services/org/client/search?_s=cross_ref_key==ClientId;cross_ref_value=="8cdc9a4f-3518-4941-9b62-5bc88bac5f3c;buId==0;martId==0',
info: 'System encountered some internal error.',
severity: 'ERROR',
category: 'DATA',
causes: [],
errorIdentifiers: {}
}
The error mentions index 172 but I'm not exactly sure what it's referring to. Having looked at their docs here I'm following the implementation to the letter.
Here is my request for XML:
{
url: 'https://sandbox.walmartapis.com/v3/token',
data: '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n' +
'<grant_type>client_credentials</grant_type>',
options: {
headers: {
Authorization: 'Basic <base64String>=',
Accept: 'application/xml',
'Content-Type': 'application/xml',
'WM_SVC.NAME': 'Walmart Marketplace',
'WM_QOS.CORRELATION_ID': 'be1ff777-9c7b-4ca2-8b9c-ac31696dbf79',
}
},
method: 'post'
}
But this is also fails.
Does anyone know why these requests may be failing and perhaps provide a working example in JS of a request to authenticate with the API?
var request = require('request');
var options = {
'method': 'POST',
'url': 'https://sandbox.walmartapis.com/v3/token',
'headers': {
'WM_SVC.NAME': 'Walmart Marketplace',
'WM_QOS.CORRELATION_ID': 'test',
'Accept': 'application/json',
'Authorization': 'Basic afafaf...',
'WM_SVC.VERSION': ' 1.0.0',
'Content-Type': 'application/x-www-form-urlencoded'
},
form: {
'grant_type': 'client_credentials'
}
};
request(options, function (error, response) {
if (error) throw new Error(error);
console.log(response.body);
});
This works for me. Make sure you have the Authorization build correctly. it is in the format "Basic Base64encode(cliendId:clientSecret)"
I think the they way you are sending the grant_type attribute is incorrect.
I need to call a bunch of APIs and map their response data to respective data sources. I am able to do so using separate fetch() calls to the APIs. However, I want use Promise.all() to load data from all the APIs before displaying them in the app. I am however unable to successfully do so. Following is the snippet:
componentDidMount() {
this.fetchAPIs(); //function to call APIs
this.loadFontAsync(); //function to load custom font
}
fetchAPIs = async () => {
console.log('Fetching APIs')
await Promise.all([
fetch('http://192.168.0.111:8080/endpoint1', {
method: 'post',
mode: 'cors',
headers: {
'Accept': 'application/json',
'Content-type': 'application/json'
},
body: JSON.stringify({
"customerNo": this.state.custId,
})
}),
fetch('http://192.168.0.111:8080/endpoint2', {
method: 'post',
mode: 'cors',
headers: {
'Accept': 'application/json',
'Content-type': 'application/json'
},
body: JSON.stringify({
"customerNo": this.state.custId,
})
}),
fetch('http://192.168.0.111:8080/endpoint3', {
method: 'get',
mode: 'cors',
headers: {
'Accept': 'application/json',
'Content-type': 'application/json'
}
}),
fetch('http://192.168.0.111:8080/endpoint4', {
method: 'post',
mode: 'cors',
headers: {
'Accept': 'application/json',
'Content-type': 'application/json'
}
,
body: JSON.stringify({
"customerNo": this.state.custId,
})
})
])
.then((response) => Promise.all(response.map(res => res.json())))
.then((response) => {
this.setState({
//mapping response to dataSources chronologically
dataSource3: response[0],
dataSource1: response[1],
dataSource2: response[2],
dataSource4: response[3],
isLoading: false // to check if APIs are loaded
})
})
.catch((error) => {
Alert.alert("Promise not fulfilled");
console.error(error);
});
}
When I check the logs in the server where the API is hosted, there is no hit to any of the endpoints on executing this code.
Could anyone suggest on what I am missing?
Building a Django Rest Framework. when I user 'curl' to call the API with a valid token it works:
curl -viL -H "Authorization: Token 65c38dfe0c910b727197683aebdcc1c67c1b7aa3" http://127.0.0.1:8000/api/habit/
The same API call via my javascript call, fails and Django see it as an anonymous user and errors out.
fetchHabits: function() {
console.log('Token '+this.authToken.token);
fetch('http://127.0.0.1:8000/api/habit/?format=json',{
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Token '+this.authToken.token
}
})
.then(response => response.json())
.then(json => this.habits = json)
},
I have proven that the right token is sent and received. I am assuming because CURL works that the Django code is working, so that the bug is in the header on the Javascript side.
Can anyone help please?
There was a missing component in the HTTP header, it needed to have "cedentials: 'included'"
The final header was :
fetch('http://127.0.0.1:8000/api/habit/?format=json',{
method: 'GET',
headers: {
'Accept': '*/*',
'Content-Type': 'application/json',
'Authorization': 'Token '+this.authToken.token
},
credentials: 'include'
})
I am trying to upload file(image) from my react-native app to backend server. The RESTFUL backend server accepts file send via PUT method on a specific url. I am stuck on react-native trying to find the proper way to send file via PUT method.
I am trying to replicate behavior of
curl -X PUT -T "/path/to/file" "http://myputserver.com/puturl.tmp"
I found XMLHttpRequest method of doing this on a browser but won't work on react-native. Have anyone gone through this please help!!!
fetch('https://mywebsite.com/endpoint/', {
method: 'PUT',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
firstParam: 'yourValue',
secondParam: 'yourOtherValue',
}),
})
.then((response) => response.json())
.then((responseJson) => {
alert(responseJson)
})
.catch((error) => {
console.error(error)
})
reference
reference 2
Fetch
Use the fetch api, which is supported by React Native.
Below is an example of the official documentation.
Fetch supports PUT, according to the specs.
fetch('https://mywebsite.com/endpoint/', {
method: 'PUT',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
firstParam: 'yourValue',
secondParam: 'yourOtherValue',
})
})
You can use the PUT like the answer above. You might be missing the 'Content-Type': 'multipart/form-data;'.
const config = {
method: 'PUT',
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data;',
'Authorization': 'Bearer ' + 'SECRET_OAUTH2_TOKEN_IF_AUTH',
},
body: data,
}
Some more information in this blog post:
http://snowball.digital/Blog/Uploading-Images-in-React-Native