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)
Related
I´m refering to this post: Fetch: POST JSON data
I´ve copied the code which is linked down below.
My question is, is it possible to save for example "Content-Length" which i get as a response in the JSON-file as a variable with which i can continue to work?
Looking forward!
Thanks already!
fetch('https://httpbin.org/post', {
method: 'POST',
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json'
},
body: JSON.stringify({a: 7, str: 'Some string: &=&'})
}).then(res => res.text())
.then(res => console.log(res));
And my result is:
{
"args": {},
"data": "{\"a\":7,\"str\":\"Some string: &=&\"}",
"files": {},
"form": {},
"headers": {
"Accept": "application/json, text/plain, */*",
"Accept-Encoding": "br, gzip, deflate",
"Accept-Language": "*",
"Content-Length": "32",
"Content-Type": "application/json",
"Host": "httpbin.org",
"Sec-Fetch-Mode": "cors",
"User-Agent": "undici",
"X-Amzn-Trace-Id": "Root=1-6388fb1d-3f7791960bdce04f36356182"
},
"json": {
"a": 7,
"str": "Some string: &=&"
},
"origin": "79.208.157.109",
"url": "https://httpbin.org/post"
}
Of course you can - just access it and store it in a variable:
const example = async() => {
const res = await fetch('https://httpbin.org/post', {
method: 'POST',
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json'
},
body: JSON.stringify({a: 7, str: 'Some string: &=&'})
})
const response = await res.json()
const contentLength = response.headers['Content-Length'];
displayContentLength(contentLength);
}
function displayContentLength(length) {
console.log('The content length is: ' + length);
}
example();
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);
})
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 have a small Spotify app that I am trying to convert to use the axios http library. I am having an issue with the callback when logging in. Up to this point I have been using request like is in all of the Spotify documentation. Everything works fine with request, but even though everything looks the same with axios, I get a 500 Internal Server Error. Here is my code to make the http request:
var authOptions = {
method: 'POST',
url: 'https://accounts.spotify.com/api/token',
form: {
code: code,
redirect_uri: REDIRECT_URI,
grant_type: 'authorization_code'
},
headers: {
'Authorization': 'Basic ' + (new Buffer(CLIENT_ID + ':' + CLIENT_SECRET).toString('base64'))
},
json: true
};
axios(authOptions).then(res => {
console.log(res)
})
I can pass the same authOptions object to the request library everything works fine. Here is my request from axios logged out to the console.
{
method: 'POST',
url: 'https://accounts.spotify.com/api/token',
form:
{ code: 'changedthecode',
redirect_uri: 'http://localhost:8888/callback',
grant_type: 'authorization_code' },
headers: { Authorization: 'Basic changedthecode=' },
json: true,
timeout: 0,
transformRequest: [ [Function] ],
transformResponse: [ [Function] ],
withCredentials: undefined
}
And here is my response with the axios library:
{ data: { error: 'server_error' },
status: 500,
statusText: 'Internal Server Error',
headers:
{ server: 'nginx',
date: 'Fri, 04 Dec 2015 14:48:06 GMT',
'content-type': 'application/json',
'content-length': '24',
connection: 'close' },
config:
{ method: 'POST',
headers: { Authorization: 'Basic changedthecode' },
timeout: 0,
transformRequest: [ [Function] ],
transformResponse: [ [Function] ],
url: 'https://accounts.spotify.com/api/token',
form:
{ code: 'changedthecode',
redirect_uri: 'http://localhost:8888/callback',
grant_type: 'authorization_code' },
json: true,
withCredentials: undefined }
}
The only option that I didn't know about from axios was withCredentials, and it didn't work when it was set to false or true. What else am I missing?
The problem is that I was posting a form and was not encoding it when going across the wire and I was not setting the Content-Type. I changed my authOptions to:
var authOptions = {
method: 'POST',
url: 'https://accounts.spotify.com/api/token',
data: querystring.stringify({
grant_type: 'refresh_token',
refresh_token: refreshToken
}),
headers: {
'Authorization': 'Basic ' + (new Buffer(CLIENT_ID + ':' + CLIENT_SECRET).toString('base64')),
'Content-Type': 'application/x-www-form-urlencoded'
},
json: true
};
and everything worked fine.