How to write a axios get command correctly to curruncy rate api? - axios

I have a problem like this. I am new to react stuff. I used axios HTTP request npm package to write API call. But when I console log the response it says like this.
{data: {…}, status: 200, statusText: "OK", headers: {…}, config: {…}, …}
config: {adapter: ƒ, transformRequest: {…}, transformResponse: {…}, timeout: 0, xsrfCookieName: "XSRF-TOKEN", …}
data:
error: {code: 101, type: "missing_access_key", info: "You have not supplied an API Access Key. [Required format: access_key=YOUR_ACCESS_KEY]"}
success: false
__proto__: Object
headers: {content-type: "application/json; Charset=UTF-8"}
request: XMLHttpRequest {onreadystatechange: ƒ, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …}
status: 200
statusText: "OK"
__proto__: Object
It says that I am not providing API_key. This is how I have written my code.
const access_key ='my_key'
axios.get(`http://data.fixer.io/api/2013-12-24
? access_key =${access_key} & base = LKR & symbols = ETH`)
.then(res=>{
console.log(res);
})
Can Someone help me to solve this problem?. Thank You.

An alternative
In case you're feeling tired of using a quite long string url which easily causes mistakes, the axios library already supports an alternative. Using like this:
const access_key ='my_key'
axios.get('http://data.fixer.io/api/2013-12-24', {
params: {
access_key: access_key,
base: LKR,
symbols: ETH
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
For reference: https://github.com/axios/axios#example

Related

404 Not Found on Github API using github.rest.git.createRef

I use the following code inside a Github Action workflow file:
await github.rest.git.createRef({
owner: context.repo.owner,
repo: context.repo.repo,
ref: 'refs/heads/' + '${{ github.event.inputs.combineBranchName }}',
sha: baseBranchSHA
});
The code results into a 404 :
RequestError [HttpError]: Not Found
at /home/runner/work/_actions/actions/github-script/v6/dist/index.js:6173:21
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async eval (eval at callAsyncFunction (/home/runner/work/_actions/actions/github-script/v6/dist/index.js:13340:16), <anonymous>:71:3)
at async main (/home/runner/work/_actions/actions/github-script/v6/dist/index.js:13436:20) {
status: 404,
response: {
url: 'https://api.github.com/repos/myusername/myrepo/git/refs',
status: 404,
headers: {
...
},
data: {
message: 'Not Found',
documentation_url: 'https://docs.github.com/rest/reference/git#create-a-reference'
}
},
request: {
method: 'POST',
url: 'https://api.github.com/repos/myusername/myrepo/git/refs',
headers: {
accept: 'application/vnd.github.-preview+json',
'user-agent': 'actions/github-script octokit-core.js/3.6.0 Node.js/16.13.0 (linux; x64)',
authorization: 'token [REDACTED]',
'content-type': 'application/json; charset=utf-8'
},
body: '{"ref":"refs/heads/combined-prs-branch","sha":"a3167bb784fa5d045bbad57545a7a96c5d89be4f"}',
request: { agent: [Agent], hook: [Function: bound bound register] }
}
}
I'm using a PAT that has access to public repo.
I went from 403 error with GITHUB_TOKEN to 404 with PAT_TOKEN.
So I guess I solved the permission issue but why is it 404 now ?
I can access the URL https://api.github.com/repos/myusername/myrepo/git/refs in a browser.

axios POST get 400

This is driving me crazy!
Exactly the same POST request works fine in Insomina per screenshot below:
The only header Insomina has is: Content-Type: application/json.
Now, the same request in code (I even copied the code generated from Insomnia for axios) via axios in Typescript:
const saveReqConfig: AxiosRequestConfig = {
method: 'POST',
url: 'THE SAME URL USED IN Insomina',
timeout: 3000,
data: {
name: `TestName`,
uri: `TestURI`,
statusCode: '200',
simulatedLatency: '0',
contentType: "application/json",
tags: '',
response: 'testing...',
type: 'VA',
},
headers: {
'Content-Type': 'application/json',
}
}
const normalAxios = axios.create();
const test = await normalAxios.request(saveReqConfig);
Don't understand why I am getting AxiosError: Request failed with status code 400 from code but the same request works fine in Insomina.
I think you did not set the headers correctly or you may not have setup the .create() properly.
Something like this:
const instance = axios.create({
url: '/post',
baseURL: 'https://httpbin.org',
method: 'POST',
timeout: 1000,
headers: {
Content-Type: 'application/json' // <- set your headers
}
});
let res = await instance.request({ // <- pass the data here
data: { // This should be whatever you want to post to this url. I just copied what you had.
name: `TestName`,
uri: `TestURI`,
statusCode: '200',
simulatedLatency: '0',
tags: '',
response: 'testing...',
type: 'VA',
}
});
Are you sure you need to use the .create() factory? The normal post like this might suite your needs better?
const data= { title: 'Axios POST Request Example' };
const headers = {
Content-Type: 'application/json'
};
axios.post('url', data, { headers }).then(response => console.log(response.data.title);
Posting here in case it helps someone.
It turned out that I couldn't post the request programmatically is because of lack of a TLS certificate. I didn't know that Insomnia has the option to disable the TLS and that's why it works in Insomnia.
To disable TLS (Do NOT do this in production!) from node with axios, create an instance of axios with a https agent setting rejectedUnauthorized to false e.g.
const instance = axios.create({
httpsAgent: new https.Agent({
rejectedUnauthorized: false
})
});
Also, set the environment variable as:
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';

Creating new document with Firestore REST API and Local Emulator Suite for Integration Test, Returning Error 400: Problem with Request Body?

I recently posted a question regarding creating a document in a collection in the local emulator suite using a HTTP Post Request with Axios.
Creating new document with Firestore REST API and Local Emulator Suite, Returning Error 404: Problem with Path Parameter
My previous error was a 404 error with the URL path parameter. Since making changes to that, now I’m receiving a 400 error. The following is the code:
First, using a post request to create an authenticated user ID token and storing that in a variable. No issues here.
//HTTP Post Request to create an auth ID, storing ID Token in variable
const createUserResponse = await axios.post(createUserInstance.url, createUserInstance.data, createUserInstance.config);
const userIdToken = createUserResponse.data.idToken;
const userLocalId = createUserResponse.data.localId;
console.log(userIdToken);
console.log(userLocalId);
Second, writing the request body. I’ve modified the URL which works now. I’ve also re-modified the data body to make sure it’s in the correct format.
Wondering if the issue is in:
the way I’ve written the query parameters (do I need to specific the new document name? is the API key the problem?)
the formatting of the data request body : according to the documentation a new document is automatically generated. I’d presume fields would be read as containing the key-value pairs to include in the document fields.
the formatting of the headers. I’ve checked and re-checked this. My userIDToken contains a string
//create a document in the user collection
//request body
const createDocumentInstance : createPostRequest = {
url: 'http://localhost:8080/v1beta1/projects/okane-crud-dev/databases/(default)/documents/test?key=<API_KEY>',
data: {
'fields': {
'localId': 'hello',
}
},
//directly pasted IdToken as using the variable resulted in problem with ' ' error
config: {
'headers':
{
'Content-Type': 'application/json',
'Authorization': `Bearer ${userIdToken}`,
}
}};
To make sure of what I was looking at, I logged the entire request in my console. This is what it looks like.
console.log
{
url: 'http://localhost:8080/v1beta1/projects/okane-crud-dev/databases/(default)/documents/test?key=AIzaSyCQSnirvajGL5Uok34OgEn7tF1S_tp5sa0',
data: { fields: { localId: 'hello' } },
config: {
headers: {
'Content-Type': 'application/json',
Authorization: 'Bearer eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJlbWFpbCI6Im15ZW1haWxAZW1haWwuY29tIiwiZW1haWxfdmVyaWZpZWQiOmZhbHNlLCJhdXRoX3RpbWUiOjE2NjU0NTQ2MDgsInVzZXJfaWQiOiI1Vmt3TUtRc1k0THJRTkRWaXpFYmdnYnExOVNyIiwiZmlyZWJhc2UiOnsiaWRlbnRpdGllcyI6eyJlbWFpbCI6WyJteWVtYWlsQGVtYWlsLmNvbSJdfSwic2lnbl9pbl9wcm92aWRlciI6InBhc3N3b3JkIn0sImlhdCI6MTY2NTQ1NDYwOCwiZXhwIjoxNjY1NDU4MjA4LCJhdWQiOiJva2FuZS1jcnVkLWRldiIsImlzcyI6Imh0dHBzOi8vc2VjdXJldG9rZW4uZ29vZ2xlLmNvbS9va2FuZS1jcnVkLWRldiIsInN1YiI6IjVWa3dNS1FzWTRMclFORFZpekViZ2dicTE5U3IifQ.'
}
}
}
Finally, making the post request on Axios. Exact same syntax as my previous post request.
//Post Request to create a document
const createDocument = await axios.post(createDocumentInstance.url, createDocumentInstance.data, createDocumentInstance.config);
const docReference = createDocument.data;
console.log(docReference);
When running this, the following error is returned:
{
message: 'Request failed with status code 400',
name: 'Error',
description: undefined,
number: undefined,
fileName: undefined,
lineNumber: undefined,
columnNumber: undefined,
stack: 'Error: Request failed with status code 400\n' +
' at createError (/Users/georgettekoo/Documents/Code/Okane/Okane-Firebase-Backend-Deprecated/functions/node_modules/axios/lib/core/createError.js:16:15)\n' +
' at settle (/Users/georgettekoo/Documents/Code/Okane/Okane-Firebase-Backend-Deprecated/functions/node_modules/axios/lib/core/settle.js:17:12)\n' +
' at IncomingMessage.handleStreamEnd (/Users/georgettekoo/Documents/Code/Okane/Okane-Firebase-Backend-Deprecated/functions/node_modules/axios/lib/adapters/http.js:293:11)\n' +
' at IncomingMessage.emit (node:events:539:35)\n' +
' at endReadableNT (node:internal/streams/readable:1344:12)\n' +
' at processTicksAndRejections (node:internal/process/task_queues:82:21)',
config: {
transitional: {
silentJSONParsing: true,
forcedJSONParsing: true,
clarifyTimeoutError: false
},
adapter: [Function: httpAdapter],
transformRequest: [ [Function: transformRequest] ],
transformResponse: [ [Function: transformResponse] ],
timeout: 0,
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
maxBodyLength: -1,
validateStatus: [Function: validateStatus],
headers: {
Accept: 'application/json, text/plain, */*',
'Content-Type': 'application/json',
Authorization: 'Bearer eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJlbWFpbCI6Im15ZW1haWxAZW1haWwuY29tIiwiZW1haWxfdmVyaWZpZWQiOmZhbHNlLCJhdXRoX3RpbWUiOjE2NjU2MzAwMTUsInVzZXJfaWQiOiJEMTBoblpsek9nQWR0ZlJlNm1VUDBOY2ZtNm5pIiwiZmlyZWJhc2UiOnsiaWRlbnRpdGllcyI6eyJlbWFpbCI6WyJteWVtYWlsQGVtYWlsLmNvbSJdfSwic2lnbl9pbl9wcm92aWRlciI6InBhc3N3b3JkIn0sImlhdCI6MTY2NTYzMDAxNSwiZXhwIjoxNjY1NjMzNjE1LCJhdWQiOiJva2FuZS1jcnVkLWRldiIsImlzcyI6Imh0dHBzOi8vc2VjdXJldG9rZW4uZ29vZ2xlLmNvbS9va2FuZS1jcnVkLWRldiIsInN1YiI6IkQxMGhuWmx6T2dBZHRmUmU2bVVQME5jZm02bmkifQ.',
'User-Agent': 'axios/0.24.0',
'Content-Length': 30
},
method: 'post',
url: 'http://localhost:8080/v1beta1/projects/okane-crud-dev/databases/(default)/documents/test?key=AIzaSyCQSnirvajGL5Uok34OgEn7tF1S_tp5sa0',
data: '{"fields":{"localId":"hello"}}'
},
code: undefined,
status: 400
}
Not sure what I'm missing and where the issue is. Does anyone have any hints?

axios patch updates website state, but it doesnt update mongo db state

I have been trying to edit/update product on my website trough axios patch method. When i submit my form i get status 200 OK , and data on the website is updated, until i refresh the page. When i refresh it old values return and db is not updated, which means that there is a problem with communication with db.
I am using atlas mongodb, and i had similar problem with axios delete method, but the problem was in Atlas IP restrictions which i have solved now, but problem with axios patch remains.
my vuejs patch method:
handleEditForm(_id) {
axios.patch(`http://localhost:3000/api/ropes/${_id}`, this.ropes)
.then((res) => {
console.log(res)
this.showModal = false
}).catch(error => {
console.log(error)
})
},
}
server side patch:
router.patch('/:ropeId', async (req, res) => {
try {
const updatedRope = await Rope.updateOne({_id: req.params.ropeId}, {
$set: {
image:req.body.image,
title: req.body.title,
description: req.body.description,
diameter:req.body.diameter,
price:req.body.price,
cartQuantity:req.body.cartQuantity,
totalQuantity:req.body.totalQuantity
}
})
res.json(updatedRope)
} catch (err) {
res.json({message: err})
}
})
console log:
adapter: function xhrAdapter(config)
​​
data: "[{\"_id\":\"60171a1bd86adc454b3b757a\",\"title\":\"Polyester sinking ropes\",\"description\":\"Polyester sinking rope Polyester sinking rope Polyester sinking rope Polyester sinking rope Polyester sinking rope\",\"image\":\"\",\"diameter\":\"22mm\",\"price\":35,\"cartQuantity\":1,\"totalQuantity\":\"1000\",\"date\":\"2021-01-31T20:59:07.452Z\",\"__v\":0}]"
​​
Object { data: {…}, status: 200, statusText: "OK", headers: {…}, config: {…}, request: XMLHttpRequest }
headers: Object { Accept: "application/json, text/plain, */*", "Content-Type": "application/json;charset=utf-8" }
​​
maxBodyLength: -1
​​
maxContentLength: -1
​​
method: "patch"
​​
timeout: 0
``

SyntaxError: missing ; before statement in kendoui

how come when i'm clicking on the update button popup kendo grid , this error ocurrs?
The error in Firefox browser is in this form : SyntaxError: missing ; before d.0=value
and in Chrome browser : Uncaught SyntaxError: Unexpected number
I've uploaded a video regarding this error for elaboration n stuff
Jsfiddle Code
Video
Code
transport: {
read: {
url: 'https://dl.dropboxusercontent.com/sh/u9oxg5f6uweqh40/CbR3pNVg04/documentj',
dataType: 'json',
type: 'get',
cache: false
},
update: function(e) { return true; }
}
save: function (e) {
var that = this;
$.ajax({
url: '/echo/json',
type: e.model.id == null ? 'POST' : 'PUT',
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify(e.model),
success: function (data) {
// Alertify.log.success(data);
console.log('ok dadasaved');
that.refresh();
},
error: function (data) {
// Alertify.log.error(data);
console.log('no datasaved');
that.cancelRow();
}
});
}
You should provide more code to detect what's wrong with your code, but read this may help you:
Such error occurs when the transport definitions are inconsistent. In other words, if you would like to use custom transport method, all transport types should be defined as functions.
Having a standard read transport and custom update is not supported. Please configure all transports as functions and let me know if the error still occurs.
I had the same error and for me the problem was that the dataType option was not set for all transport methods. I marked that line with a comment below:
var linksDataSource = new kendo.data.DataSource({
transport: {
read: {
dataType: "json",
url: 'read-url',
type: "get"
},
destroy: {
dataType: "json", /* <============ THIS LINE WAS MISSING */
url: 'delete-url',
type: "delete"
},
update: {
dataType: "json",
url: 'update-url',
type: "post"
},
create: {
dataType: "json",
url: 'create-url',
type: "post",
complete: function () {
$("#searchResult").data("kendoGrid").dataSource.read();
}
},
/* ... */