I'm not sure if the header or the body are configured incorrectly.
Any thoughts on whether to change the headers or maybe the body is misconfigured?
const axios = require('axios');
const url = '/my_url';
const auth = {
username: username,
password: password
};
const requestbody = {
To: 'phone',
From: 'phone 2'
};
const headers = {
'Content-Type': 'application/x-www-form-urlencoded',
}
const config = {
auth: auth,
headers: headers
}
try {
const response = await axios.post(url, {data: requestbody}, config);
console.log(response);
} catch (error) {
console.error(error);
}
Error like:
message: 'Missing required parameter To in the post body'
you need to stringify parameters and then pass directly
const querystring = require('query-string');
const query = querystring.stringify({
To: 'phone',
From: 'phone 2'
});
let options = {
headers: {
'Authorization': AUTH_HEADER,
'Content-Type': 'application/x-www-form-urlencoded'
}
};
let axios_res = await post(url, query , options);
Related
My api is as follows..
const { URL, URLSearchParams } = require("url");
async callSendApi(requestBody) {
let url = new URL(`${API_URL}/${PAGE_ID}/messages`);
url.search = new URLSearchParams({
access_token: `${PAGE_ACCESS_TOKEN}`,
});
console.warn("Request body is\n" + JSON.stringify(requestBody));
let response = await axios.post(url, {
headers: { "Content-Type": "application/json" },
body: JSON.stringify(requestBody),
});
if (!response.ok) {
consoleconst`Unable to call Send API: ${response.statusText}`,
await response.json();
}
}
The error I get :
message: 'Unknown path components: /messagesaccess_token="access_token"
I cannot find any wrong in this api. but still I get above error.. so I tried following...
async callSendApi(requestBody) {
let url = new URL(`${API_URL}/${PAGE_ID}/messages`);
console.warn("Request body is\n" + JSON.stringify(requestBody));
let response = await axios.post(url, {
headers: { "Content-Type": "application/json" },
body: JSON.stringify(requestBody),
access_token: `${PAGE_ACCESS_TOKEN}`,
});
if (!response.ok) {
consoleconst`Unable to call Send API: ${response.statusText}`,
await response.json();
}
}
then I get a error saying that cannot set headers after sending to the client..
please help!
I'm currently trying to incorporate Spotify's API into my project but I'm having problems fetching the data.
My token is returned in the console which is great but my call to return some data doesn't work.
I'm getting an error :
error:
message: "Only valid bearer authentication supported"
status: 400
[[Prototype]]: Object
[[Prototype]]: Object
Here's what I have so far. Maybe its a simple fix.
// Token
const CLIENT_ID = 'HIDDEN';
const CLIENT_SECRET = 'HIDDEN';
let authParameters = {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: 'grant_type=client_credentials&client_id=' + CLIENT_ID + '&client_secret=' + CLIENT_SECRET
}
async function getToken() {
let myToken = await fetch('https://accounts.spotify.com/api/token', authParameters)
let tokenReturn = await myToken.json()
console.log(tokenReturn.access_token)
}
// Request
async function searchData() {
const baseUrl = 'https://api.spotify.com/v1/browse/new-releases';
let ArtistParameters = {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + tokenReturn
},
}
let artistID = await fetch(baseUrl, ArtistParameters)
let artistList = await artistID.json()
console.log(artistList);
}
useEffect(() => {
getToken()
searchData()
}, [])
when I'm trying to call the request in front node, I'm getting error in my backend node " RequestError: Error: Invalid URI "undefined"" , it seems like backend node request is not getting the data form my frontend node request.
knowing that uploadLink already have a value and in my browser console the frontend request looks ok
my backend request code
const ThumbnailUpload = async (req, res) => {
const { Uploadlink } = req.body;
const { selectedFile } = req.body;
const clientServerOptions = {
uri: `${Uploadlink}`,
body: JSON.stringify({
name: selectedFile,
}),
method: 'PUT',
headers: {
'Content-Type': ' application/json',
Accept: 'application/vnd.vimeo.*+json;version=3.4',
Authorization: getVimeoAuthorization(),
},
};
request(clientServerOptions, function (error, response) {
if (error) {
res.send(error);
} else {
const body = JSON.parse(response.body);
res.send(body);
}
console.log(Uploadlink);
});
};
and my frontend code is
const handleSubmit = (event) => {
event.preventDefault();
const formData = new FormData();
formData.append(
'selectedFile',
new Blob([selectedFile], { type: 'image/jpg, image/png, or image/gif' }),
);
formData.append('uploadLink', uploadLink);
const headers = {
'Content-Type': 'image/jpg, image/png, or image/gif',
Accept: 'application/vnd.vimeo.*+json;version=3.4',
};
try {
axios
.post(`${backendPostPath}/thumbnail-upload`, formData, {
headers,
})
.then((response) => {
applyThumbnial();
console.log(response);
});
} catch (error) {
console.log(error);
}
};
any advise ?
change:
const { Uploadlink } = req.body;
to:
const { uploadlink } = req.body;
make variable consistent throughout the code
EDIT
also, since you're uploading a file, you need to use upload middleware before request handler, and file will be within req.file:
route.post('/thumbnail-upload', upload.single('selectedFile'), ThumbnailUpload);
//... handler..
const selectedFile = req.file;
I have some code that looks like this in Next JS
const resApp = await fetch('/api/club/createsignalapp', {
body: JSON.stringify({
name: event.target.name.value,
}),
headers: {
'Content-Type': 'application/json',
},
method: 'POST',
})
const appResult = await resApp.json()
--createsignalapp
export default async (req, res) => {
var mydata
var createApp = function (data) {
var headers = {
'Content-Type': 'application/json; charset=utf-8',
Authorization: `Basic APIKKEY`,
}
var options = {
host: 'onesignal.com',
port: 443,
path: '/api/v1/apps',
method: 'POST',
headers: headers,
}
var https = require('https')
var myreq = https.request(options, function (myres) {
myres.on('data', function (data) {
mydata = JSON.parse(data)
res.statusCode = 200
res.json({
response: {
boolean: true,
alert: '',
message: '',
},
data: mydata
})
})
})
myreq.on('error', function (e) {
console.log(e)
})
myreq.write(JSON.stringify(data))
myreq.end()
}
var message = {
name: req.body.name
}
createApp(message)
}
This hits the error API resolved without sending a response for /api/club/createsignalapp, this may result in stalled requests.
I'm not sure how to do this correctly as i'm getting confused with the awaits and asyncs and requests everywhere.
Happy to hear suggestions.
Thanks
I'm trying to switch from request.js to got.js. I expect to see the got.js implementation authenticate similarly to how the request.js library does. But, instead, I get the following error.
auth no longer supported. Replaced by username and password.
There is no mention of bearer tokens on the docs page.
So how do I authenticate my request using bearer tokens using got.js? Or what am I doing wrong?
Current code: request.js, working
const request = require('request');
const module.exports = config => {
const options = {
auth: {
bearer: config.secret,
},
};
const result = await new Promise(( resolve, reject, ) => {
request.get( url, options, ( error, response, body, ) => {
...
New code: got.js, throws error
const got = require('got');
module.exports = async config => {
const options = {
auth: {
bearer: config.secret,
},
};
const result = await got(url, options);
...
}
This should be worked, if I'm not wrong
let token = 'your token'
const options = {
headers: {
'Authorization': `Bearer ${token}`
}
};
worked for me !!
router.get('/product', (req,res)=>{
const dataStream = got.stream({
url: "http://localhost:8000/products",
method: "GET",
hooks: {
beforeRequest: [
options => {
var token= 'Bearer ' + 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpYXQiOjE2MTkzODA0NjIsImV4cCI6MTYxOTM4NDA2Mn0.JoJbRpPniGuMbwULEtts7I19QxEImvarT6AoqVuNb9w'
options.headers['Authorization'] = token;
}
]
}
});
pipeline(dataStream, res, (err) => {
if (err) {
console.log(err);
res.sendStatus(500);
}
});
});