This question already has answers here:
Axios Http client - How to construct Http Post url with form params
(5 answers)
Closed 3 years ago.
I'm trying to POST on an API but Axios.post keeps failing, while XHR works. I know I have to set the request's headers with UTF-8 but it seems Axios is not recognizing it.
I know I need to set 'application/x-www-form-urlencoded; charset=UTF-8' on my header request for this is API was made in Flask and the owner did not configure this part of it. (And because it works with XHR).
The code working is:
const post = (url, params) => {
const http = new XMLHttpRequest();
http.open("POST", url, true);
http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded; charset=UTF-8');
http.onreadystatechange = () => {
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(params);
};
So I googled to know how translante #setRequestHeader to Axios.post() and found these links: https://github.com/axios/axios/issues/858 and https://github.com/axios/axios/issues/827.
Then I tried something like this:
const headers = {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
};
const post = ({ data, endpoint }) => axios
.post(endpoint, data, { headers })
.then(request => request.data);
This:
const headers = {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
};
const post = ({ data, endpoint }) => axios
.post(endpoint, data, headers)
.then(request => request.data);
And this:
const headers = {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
};
const post = ({ data, endpoint }) => axios({
method: "post",
url: endpoint,
data,
headers
}).then(request => request.data);
But every single one of then failed with an error 400.
So, how should I translate http.setRequestHeader() to Axios?
Try the code below.
From https://github.com/axios/axios/issues/858
const endpoint = 'http://localhost/test.php'; // eg.
axios.post(endpoint,
querystring.stringify({
paramter: 'value',
}),
{
headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }
});
Related
Hello I have tried to use the instagram api to get a connection token. I first tested it on postman and this is what I did:
I used this link to make a request post to the instagram api:
https://api.instagram.com/oauth/access_token?client_id=clientid&client_secret=clientsecret&grant_type=authorization_code&redirect_uri=https://mysite/&code=thecode
The api gives me an error: Missing required field client_id
But when I set the content type to x-www-form-urlencoded everything works fine on postman.
So I tried to do the same thing in javascript with the node module request. I tried to do the same thing as on postman with the module but it does not work... Here is my code:
request(`https://api.instagram.com/oauth/access_token?client_id=clientid&client_secret=clientsecret&grant_type=authorization_code&redirect_uri=https://mysite/&code=` + code, {
method: 'POST',
headers: {"Content-Type": "x-www-form-urlencoded"}
}, (error, response, body) => {
console.log('body:', body)
})
As per MDN, the content type should be application/x-www-form-urlencoded
https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST
Update:
You should read the node doc : https://nodejs.dev/learn/making-http-requests-with-nodejs
Get method:
const https = require('https');
const options = {
hostname: 'api.instagram.com',
path: '/oauth/access_token?client_id=clientid&client_secret=clientsecret&grant_type=authorization_code&redirect_uri=https://mysite/&code=thecode',
method: 'GET',
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"Accept": "Accept-Encoding"
}
};
const req = https.request(options, (res) => {
// ...
});
Post method:
var headers = {
"Content-Type": "application/x-www-form-urlencoded",
"Accept": "Accept-Encoding"
};
var options = {
url: 'https://api.instagram.com/oauth/access_token',
method: 'POST',
headers: headers
};
var form = {
grant_type:'urn:ietf:params:oauth:grant-type:jwt-bearer',
client_id: 'id',
client_secret: 'secret'
redirect_uri : 'https://mysite/&code=thecode'
};
var request = https.request(options, function(response) {
// do stuff
});
request.write(querystring.stringify(form));
request.end();
I am trying to send a post request to a URL, I did this in python with the following code and it worked like a charm and I got a [Response <200>], but since I needed to use this in a website, I switched over to JS and tried to recreate the same functionality, but for some reason I'm getting a [Response <403>] even tho all my auth tokens and headers and everything is same as the python code.
Python Code -
url = "https://discord.com/api/v8/channels/801784356711956522/messages"
auth = ""
headers = {"Authorization": auth,
'Content-Type': 'application/json', 'referer': "https://discord.com/channels/801784356217421874/801784356711956522"}
payload = {'content': 'Test' , 'nounce': 802056256326991872, 'tts': False}
response = requests.post(url, data=json.dumps(payload), headers=headers)
print(response)
JavaScript Code -
onst url = "https://discord.com/api/v8/channels/801784356711956522/messages"
const auth = ""
const headers = {"Authorization": auth,
'Content-Type': 'application/json',
'referer': "https://discord.com/channels/801784356217421874/801784356711956522"}
const options = {
headers : headers,
}
const data = JSON.stringify({'content':"Test" , 'nounce': 802056256326991872, 'tts': false})
process.env["NODE_TLS_REJECT_UNAUTHORIZED"] = 0;
const req = https.request(options, (res) => {
console.log(`statusCode: ${res.statusCode}`)
res.on('data', (d) => {
process.stdout.write(d)
})
})
req.on('error', (error) => {
console.error(error)
})
req.write(data)
req.end()
In your python code, you made a POST request but in JavaScript code, you made a GET request because you did not provide the method option.
It is specified in https.request options documentation:
method A string specifying the HTTP request method. Default:
'GET'.
To make POST request modify like this
const options = {
headers : headers,
method: "POST"
}
Also, you need to add URL since you did not provide hostname and path in the options.
const req = https.request(url, options, (res) => {
// ...
})
const querystring = require('querystring');
const https = require('https');
var postData = querystring.stringify({
'msg' : 'Hello World!'
});
var options = {
hostname: 'domain.com',
port: 443,
path: '/yow-path',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': postData.length
}
};
var req = https.request(options, (res) => {
console.log('statusCode:', res.statusCode);
console.log('headers:', res.headers);
res.on('data', (d) => {
process.stdout.write(d);
});
});
req.on('error', (e) => {
console.error(e);
});
req.write(postData);
req.end();
I am getting a 400 error when trying to send a message to twitches IRC chat with StreamElements API.
Here is my code so far I know it is incorrect but I don't know how to pass the message to twitch in order for it to accept it. I am learning ajax and will be learning jQuery in the future however if the help could please be in vanilla JS.
var data = {"message": "test"};
var token = "secret"
var xhr = new XMLHttpRequest();
xhr.addEventListener("readystatechange", function () {
if (this.readyState === this.DONE) {
console.log(this.responseText);
}
});
xhr.open("POST", "https://api.streamelements.com/kappa/v2/bot/5eab1a7fc644de5b0169703c/say");
xhr.setRequestHeader("accept", "application/json");
xhr.setRequestHeader("content-type", "application/json");
xhr.setRequestHeader("Authorization", `Bearer ${token}`);
xhr.send(data);
XMLHttpRequest is a bit old library to make HTTP request.
Consider using the new fetch API in (vanilla) JavaScript.
var data = { message: "test"};
var token = "secret"
await fetch('https://api.streamelements.com/kappa/v2/bot/5eab1a7fc644de5b0169703c/say', {
method: 'POST',
headers: {
'Content-Type': 'application/json;charset=utf-8',
'Authorization': `Bearer ${token}`
},
body: JSON.stringify(data)
})
.then(response => response.json())
.then(result => {
console.log(result)
})
.catch(err => {
console.log(err)
})
I have a scipt tag in which im making a post request to a route through axios.Axios is not sending the parameters through.
Here is the code for axios:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script type="text/javascript">
const data={'firstName':"sai"}
axios({
url: "/",
method: "post",
data: data,
})
.then(response => {
console.log(response);
})
.catch(error => console.error(error));
</script>
Here is the express side of things:
app.post("/",function(req,res){
console.log("post route");
console.log(req.body);
})
Im console.logging the data coming from the post request with the help of req.body(I also have body-parser working just fine.Tested with other normal forms).The req comes through to hit the post route.BUt the body is empty always logs "{}".
Please help me out with this.
Option 1:
Define config object
let config = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
}
}
Mandatory: Use array for params and not js object for 'application/x-www-form-urlencoded'
const params = new URLSearchParams();
params.append('PARAM1', 'VALUE1');
params.append('PARAM2', 'VALUE2');
Call post
axios.post( uri, params, config )
or
axios({
url,
headers: { 'content-type': 'application/x-www-form-urlencoded' }
data: params
})
Option 2:
Create an api instance (optional) and set default content-type
const api_local = axios.create({
baseURL: 'http://localhost:1000/myapi',
});
api_local.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
Mandatory: Use array for params and not js object for 'application/x-www-form-urlencoded'
const params = new URLSearchParams();
params.append('PARAM1', 'VALUE1');
params.append('PARAM2', 'VALUE2');
Call post
api_local.post( uri, params )
I also have body-parser working just fine.Tested with other normal forms
Normal forms submit data encoded as either multipart/form-data or application/x-www-form-urlencoded.
Axios submits data, by default, as application/json.
You need a different body parser. One which supports JSON.
(Or to submit the data in a different format)
I'm trying to make an API request using fetch(browser). A token is required in the headers to make the request.
I can make successful requests in node (server side).
However, when making requests on the browser, the OPTIONS request fails with 401.
const order_url = new URL(process.env.API_URL + 'orders/');
const params = { type: 'amazon', status: 'in_queue' };
Object.keys(params).forEach(key => url.searchParams.append(key, params[key]));
const headers = {
Authorization: 'Token ' + process.env.API_TOKEN,
'Content-Type': 'application/x-www-form-urlencoded'
};
fetch(order_url, {
headers
})
.then(response => response.json())
.then(result => {
console.log(result);
})
.catch(error => {
console.error(error)
})
The error i receive is "NetworkError when attempting to fetch resource."
What would be the correct configuration for this to work on the browser?
You are not sending headers properly.
Try this.
myHeaders = new Headers({
'Authorization': 'Token ' + process.env.API_TOKEN,
'Content-Type': 'application/x-www-form-urlencoded'
});
and then
fetch(order_url, {
headers: myHeaders,
method: 'GET'
})