On postman, I can access endpoints by adding the headers:
Key: Value ( I will insert fake figures for example)
x-mash-auth-token: gdjsjaosh-hkds-dhjsk-hjjdbahsj
I am building a react app that allows user to search endpoints, how can I include this header in my code to grant user access on UI?
axios({
url: "API URL",
method: "GET",
data: {name: "abc"},
contentType: 'application/json',
headers: {
"Access-Control-Allow-Origin": "*",
'Accept': 'application/json',
'Content-Type': 'application/json',
'Pragma': 'no-cache',
'Authorization': 'Bearer gdjsjaosh-hkds-dhjsk-hjjdbahsj',
'Access-Control-Expose-Headers': "jwt_token"
},
responseType: 'json'
})
.then(function (response) {
successCallback(response);
})
.catch(function (error) {
errorCallback(error);
})
Related
I want to call the API POST method with axios, I did it with postman with header configuration like, and it return the results
and the body request looks :
it return error when I call by axios this my script, anyone can help me what I suppose todo from the axios side ?
const header = {
headers: {
'Content-Transfer-Encoding': 'application/json',
'content-type': 'application/json',
'HTTP_API_KEY': 'xxxxx',
}
}
axios({
method: 'POST',
url: URL,
headers: header,
data : {
}
})
.then((response) => {
if (response.status !== 200) {
return res.send(respone("500", response.data.result.data))
} else {
return res.send(respone("200", response.data.result.data))
}
})
.catch((error) => {
console.log(error);
return res.send(error)
})
the error show
{
"message": "Request failed with status code 404",
"name": "AxiosError",
"config": {
"transitional": {
"silentJSONParsing": true,
"forcedJSONParsing": true,
"clarifyTimeoutError": false
},
"transformRequest": [
null
],
"transformResponse": [
null
],
"timeout": 0,
"xsrfCookieName": "XSRF-TOKEN",
"xsrfHeaderName": "X-XSRF-TOKEN",
"maxContentLength": -1,
"maxBodyLength": -1,
"env": {},
"headers": {
"Accept": "application/json, text/plain, */*",
"Content-Type": "application/json",
"Content-Transfer-Encoding": "application/json",
"HTTP_API_KEY": "xxxx",
"User-Agent": "axios/0.27.2",
"Content-Length": 2
},
"method": "post",
"url": "xxxxx",
"data": "{}"
},
"code": "ERR_BAD_REQUEST",
"status": 404
}
It seems you nested your headers inside another "headers" property.
Basically you're doing this
headers: {
headers: {
'Content-Transfer-Encoding': ...
}
}
As Zai showed in her answer you problem is your header variable:
const header = {
headers: {
'Content-Transfer-Encoding': 'application/json',
'content-type': 'application/json',
'HTTP_API_KEY': 'xxxxx',
}
}
is nested, when you do this:
axios({
method: 'POST',
url: URL,
headers: header,
data : {
}
what you are really doing is:
axios({
method: 'POST',
url: URL,
headers: headers: {
'Content-Transfer-Encoding': 'application/json',
'content-type': 'application/json',
'HTTP_API_KEY': 'xxxxx',
},
data : {
}
So your header: instead of being Content-transfer etc... is just 'headers'
try this:
const header = {
'Content-Transfer-Encoding': 'application/json',
'content-type': 'application/json',
'HTTP_API_KEY': 'xxxxx',
}
also, i recommend you to do a console.log with your api call in order to find this problems faster and compare with postman, really helpful in develop phase (just use it in local, never push that log to production)
I am trying to add couple of image attachments in google api, I am not able to find any kind of solution for it, though I am able to send mail without it, can any one help on adding attachments.
const encodedMail = btoa([
`From: ${guest_email}\r\n`,
`To: ${toHotel}\r\n`,
`Subject: ${fullname} Sent Mail\r\n\r\n`,
`Hello There\n\n I have Just Mailed, Please find my details\n\n Name: ${fullname}\n
Phone: ${phone}\n `
].join('')).replace(/\+/g, '-').replace(/\//g, '_');
const response = await fetch(url, {
method: 'POST',
mode: 'cors',
cache: 'no-cache',
credentials: 'same-origin',
headers: {
'Authorization': 'Bearer ' + accessToken,
'Content-Type': 'application/json'
},
redirect: 'follow',
referrerPolicy: 'no-referrer',
body: JSON.stringify({
'raw': encodedMail
})
});
if (response) {
console.log(response)
}
Help would be really appreciated.
I’ve this axios request which is running ok I got http 200
import {AxiosResponse} from "axios";
const axios = require('axios').default;
const qs = require('qs');
//First query
axios({
method: 'post',
url: 'https://oauth2.-arch.mand.com/oauth2/token',
data: qs.stringify({'grant_type': 'client_credentials'}, {'scope': 'run:crud'}),
headers: {
'Accept': 'application/json',
'Authorization': 'Basic NTgwNjgtMDhhZTczOGNl',
'Content-Type': 'application/x-www-form-urlencoded',
}
}).then(function (response: AxiosResponse) {
console.log(response.data);
}).catch(function (error: any) {
console.log("Error: " + error);
});
//Second query (the only different is the scope )
axios({
method: 'post',
url: 'https://oauth2.-arch.mand.com/oauth2/token',
data: qs.stringify({'grant_type': 'client_credentials'}, {'scope': ‘exe:crud’}),
headers: {
'Accept': 'application/json',
'Authorization': 'Basic NTgwNjgtMDhhZTczOGNl',
'Content-Type': 'application/x-www-form-urlencoded',
}
}).then(function (response: AxiosResponse) {
console.log(response.data);
}).catch(function (error: any) {
console.log("Error: " + error);
});
Now I want to run two request in parallel and get the results which is response.data (the data I sent to the request / headers etc)
I’ve tried with but the response I got is like the request , I don’t get the tokens/data? Any idea
How can I use this two request in parallel ?
axios.all([{
method: 'post',
url: 'https://oauth2.-arch.mand.com/oauth2/token',
data: qs.stringify({'grant_type': 'client_credentials'}, {'scope': 'run:crud'}),
headers: {
'Accept': 'application/json',
'Authorization': 'Basic NTgwNjgtMDhhZTczOGNl',
'Content-Type': 'application/x-www-form-urlencoded',
}
},
{
method: 'post',
url: 'https://oauth2.-arch.mand.com/oauth2/token',
data: qs.stringify({'grant_type': 'client_credentials'}, {'scope': 'exe:crud'}),
headers: {
'Accept': 'application/json',
'Authorization': 'Basic NTgwNjgtMDhhZTczOGNl',
'Content-Type': 'application/x-www-form-urlencoded',
}
}]).then(axios.spread((...responses: AxiosResponse[]) =>{
const aToken = responses[0];
const bToken = responses[1];
}).catch(function (error: any) {
console.log("Error: " + error);
});
If there is a better way , please let me know
Btw, if I run this two post request separated everything is working fine
You need to provide promises to the axios.all not their config objects.
axios.all([
axios({
method: 'post',
url: 'https://oauth2.-arch.mand.com/oauth2/token',
data: qs.stringify({
'grant_type': 'client_credentials'
}, {
'scope': 'run:crud'
}),
headers: {
'Accept': 'application/json',
'Authorization': 'Basic NTgwNjgtMDhhZTczOGNl',
'Content-Type': 'application/x-www-form-urlencoded',
}
}),
axios({
method: 'post',
url: 'https://oauth2.-arch.mand.com/oauth2/token',
data: qs.stringify({
'grant_type': 'client_credentials'
}, {
'scope': 'exe:crud'
}),
headers: {
'Accept': 'application/json',
'Authorization': 'Basic NTgwNjgtMDhhZTczOGNl',
'Content-Type': 'application/x-www-form-urlencoded',
}
})
]).then(axios.spread((...responses: AxiosResponse[]) => {
const aToken = responses[0];
const bToken = responses[1];
}).catch(function(error: any) {
console.log("Error: " + error);
});
Keep in mind though that the axios.all and axios.spread are deprecated.
Use Promise.all directly
I want to call an API for register from method in React. Below is my javascript code :
fetch('http://localhost:5001/api/Account', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: "hugh.daniel#gmail.com",
name: "Hugh Daniel",
password: "1234"
})
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
And this is my controller
[HttpPost]
public ResponseModel RegisterByEmail([FromBody]UserModel user)
{
return _accountService.RegisterEmail(user);
}
But I always get these errors
I tried to add mode: 'no-cors' in my javascript code, but it makes Content-Type set to plain.
The API is working if I tested it using Postman like this
You need to combat CORS first of all. You can't make API requests against a different domain:port than the one from which it was served by development server. Are you using Webpack in your project? If yes, the easiest way is to set up API proxy by the Webpack configuration. See the doc. Something like this:
// webpack.config.js
devServer: {
port: 3030,
proxy: {
'/api': {
target: `http://localhost:5001`,
secure: false
}
}
}
Now you have to remove host:port from fetch address param and also I would add Accept header to the request settings:
fetch('/api/Account', {
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
// ...
}
)
try this
[ApiController]
[Consumes("application/json")]
[Produces("application/json")]
[Route("[controller]")]
public class TestController : ControllerBase
{}
In js:
await fetch(this.url, { method: 'POST', cache: 'no-cache', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) });
Sourse: https://pretagteam.com/question/angular-http-post-formdata-unsupported-media-type-from-c-controller
Do not use JSON.stringify in the body for sending a request and following code will do the work.
fetch('http://localhost:5001/api/Account', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: {
email: "hugh.daniel#gmail.com",
name: "Hugh Daniel",
password: "1234"
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
I am trying below javascript code to subscribe on mailchimp. flow wise working good but i am getting error like not authorize because may be i am not passing api key correctly. please help to solve my issue
var request = new Request('https://<dc>.api.mailchimp.com/3.0/lists/[listid]/members', {
method: 'POST',
mode: 'no-cors',
json: {
"email_address": "am_it#live.com",
"status": "subscribed",
},
redirect: 'follow',
headers: new Headers({
'Content-Type': 'application/json',
'Authorization': 'Basic apikey'
})
});
// Now use it!
fetch(request).then(function (data) {
console.log(data);
});
You need to add your authentification details with your username and api key. You can do it with the auth parameter:
auth: {
'user': 'yourUserName',
'pass': 'yourApiKey'
}
Just add that to your request object:
Request('https://<dc>.api.mailchimp.com/3.0/lists/[listid]/members', {
method: 'POST',
mode: 'no-cors',
json: {
"email_address": "am_it#live.com",
"status": "subscribed",
},
redirect: 'follow',
headers: new Headers({
'Content-Type': 'application/json',
'Authorization': 'Basic apikey'
}),
auth: {
'user': 'yourUserName',
'pass': 'yourApiKey'
}
});
I looked at the documentation in the getting started section of the developer mailchimp api: here and I converted the curl examples to javascript code using this page. Let me know if it worked.