I'm trying to send an automated message to discord from my account token using the axios client, it worked on a different project of mine but it doesn't work on a brand new project for some reason. Here is the code so far:
const axios = require('axios').default;
async function Post() {
const URL = `https://discord.com/api/v9/channels/${process.env.CHANNEL}/messages`
const payload = { content: "This message has been sent using axios!" }
await axios.post(URL, payload, { headers: { 'authorization': process.env.TOKEN } })
}
Post();
This is the error I'm getting:
node:internal/errors:464
ErrorCaptureStackTrace(err);
^
TypeError [ERR_HTTP_INVALID_HEADER_VALUE]: Invalid value "undefined" for header "authorization"
at ClientRequest.setHeader (node:_http_outgoing:579:3)
at new ClientRequest (node:_http_client:256:14)
at Object.request (node:https:353:10)
at RedirectableRequest._performRequest (/home/nonce/Documents/Repositories/test/node_modules/follow-redirects/index.js:279:24)
at new RedirectableRequest (/home/nonce/Documents/Repositories/test/node_modules/follow-redirects/index.js:61:8)
at Object.request (/home/nonce/Documents/Repositories/test/node_modules/follow-redirects/index.js:482:14)
at dispatchHttpRequest (/home/nonce/Documents/Repositories/test/node_modules/axios/lib/adapters/http.js:232:25)
at new Promise (<anonymous>)
at httpAdapter (/home/nonce/Documents/Repositories/test/node_modules/axios/lib/adapters/http.js:48:10)
at dispatchRequest (/home/nonce/Documents/Repositories/test/node_modules/axios/lib/core/dispatchRequest.js:58:10) {
code: 'ERR_HTTP_INVALID_HEADER_VALUE'
}
And for the record, I'm not trying to create a spammer or anything that breaks Discord's API rules.
Here are the versions I'm using, if it helps in any way:
node: v16.13.2
npm: v8.1.2
axios: v0.25.0
Found the error, I forgot to add the dotenv package all along.
Related
I'm trying to fetch an image resource that's part of a conversation message.
I've tried both FETCH as well as using AXIOS but I'm getting the same error message.
Here's an example of my FETCH request
const token = `${accountSid}:${authToken}`;
const encodedToken = Buffer.from(token).toString('base64');
let response = await fetch('https://mcs.us1.twilio.com/v1/Services/<SERVICE_SID>/Media/<MEDIA_SID>',
{
method:'GET',
headers: {
'Authorization': `Basic ${encodedToken}`,
}
});
let data = await response.json();
console.log(data);
And here's what Axios looked like
let config = {
method: 'get',
crossdomain: true,
url: 'https://mcs.us1.twilio.com/v1/Services/<SERVICE_SID>/Media/<MEDIA_SID>',
headers: {
'Authorization': `Basic ${encodedToken}`,
},
};
try {
const media = await axios(config);
console.dir(media);
} catch(err) {
console.error(err);
}
Both ways are NOT working.
After looking into it more, I found out that Chrome makes a pre-flight request and as part of that requests the allowed headers from the server.
The response that came back was this
as you can see, in the "Response Headers" I don't see the Access-Control-Allow-Headers which should have been set to Authorization
What am I missing here?
I have made sure that my id/password as well as the URL i'm using are fine. In fact, I've ran this request through POSTMAN on my local machine and that returned the results just fine. The issue is ONLY happening when I do it in my code and run it in the browser.
I figured it out.
I don't have to make an http call to get the URL. It can be retrieved by simply
media.getContentTemporaryUrl();
We are making a simple HTTP GET request to an API & noticing that when our HTTP requests error, the response body sometimes has more details then the error message. We are using the axios. We would like to access both the response and the error message from our code, but we are only seeing the error message and are unsure how to access the response. Here is our code:
Calling the API:
import { httpClient } from '../httpClient'; //AxiosInstance
type GetLocations = () => Promise<AxiosResponse<ILocation[]>>
const getLocations: GetLocations = async () => {
const url = `/Location`;
return httpClient.get(url);
}
const callAPI = async () => {
try {
const axiosResponse = await getLocations();
console.log(axiosResponse.data);
catch(error) {
// error.message has the error message, but we would like access to the http response body as well.
console.log(error)
}
}
Some Screenshots:
console.log(error):
The error object as JSON:
DevTools > Network > Our API Call > Response from same request that errored (has more info):
We would like to access this Incorrect syntax near ','. response from our catch block.
I'm currently building out an Angular 7 App, and trying to implement the following HTTP API Call Scenario:
Request for an Application Token:
https://(URL)/token
Request Type: POST
Headers:
Accept: application/json
Request Body: empty
I have a Service class in the Angular app and the code is as follows:
import { HttpClient } from '#angular/common/http';
import { HttpHeaders } from '#angular/common/http';
The requestToken function is implemented as follows:
requestToken() {
let headers = new HttpHeaders();
headers = headers.set('Accept', 'application/json');
return this.http.post(this.configUrl + '/token', headers);
}
The Service is then called in one of the components in the App:-
getToken() {
this.service.requestToken().subscribe( res => {
console.log(res);
}, error => {
console.log(error);
});
}
When I run the App, I get a 404 Not Found error in the console. I used Postman to make an API call, setting the 'Accept' header to 'application/json' and then specifying url as https://(URL)/token and I successfully get a response. But I'm unable to make it work via Angular.
Is there something else I need to do to set the header properly in Angular? Also, I have no way to check if CORS has been enabled on the API server as this is a third-party service which I'm trying to call.
Any help would be appreciated. Thanks
Solved the problem. Changed the POST call to the following:
requestToken() {
const httpHeaders = new HttpHeaders({
'Accept': 'application/json'
});
return this.http.post(this.configUrl + '/token', { body: ''}, { headers: httpHeaders });
}
Had to add an empty 'body' parameter
I am trying to access the Uber API with Axios and I am running into some trouble. I have plugged this data into Postman and I get a 200 response code with no problems. However, when I try to make an Axios call, I get response code 401 unauthorized. Can I get some help looking through my code to find out why my authorization is not working correctly with Axios?
Here is a link to the Uber API docs I am referencing. Uber API Reference
getRide_Uber = async (addressOrigin, addressDestination) => {
let origin = await geocodeAddress(addressOrigin);
let destination = await geocodeAddress(addressDestination);
const url = "https://api.uber.com/v1.2/estimates/price";
const params = {
params: {
start_latitude: origin.lat,
start_longitude: origin.lon,
end_latitude: destination.lat,
end_longitude: destination.lon
}
};
const headers = {
headers: {
Authorization: `Token ${process.env.UBER_SERVER_TOKEN}`
}
};
const response = await axios
.get(url, params, headers)
.then(function(response) {
data = response.data;
})
.catch(function(error) {
console.log(error);
});
return data;
};
Please let me know if anything needs clarification. Thanks!
try below syntax,
const config = {
headers: {
Authorization: `Token ${process.env.UBER_SERVER_TOKEN}`
}
params: {
start_latitude: origin.lat,
start_longitude: origin.lon,
end_latitude: destination.lat,
end_longitude: destination.lon
}
};
const response = await axios
.get(url, config)
.then(function(response) {
data = response.data;
})
.catch(function(error) {
console.log(error);
});
return data;
There is one more aspect axios, async/await is not supported in Internet Explorer and older browsers. So also please check your browser versions as well.
Not sure how are you getting token from env but seems the server token is not getting pass correctly, may be few extra characters while reading from env. Try to run the program first with hard coded token in program itself and once you are sure its not code issue, you can move it into config/env and then debug env read issue.
Hi I'm trying to send a POST call to the SparkPost API in a JavaScript web app. It works fine with curl and Postman, but as soon as I try sending from my localhost site I get a 401 Unauthorized error.
My current code looks like the below, but I've tried fetch as well with the same results.
sendEmail(subject, data) {
let textbody = "blah blah blah";
const url = "https://api.sparkpost.com/api/v1/transmissions";
const fetchbody = {
content: {
from: "sandbox#sparkpostbox.com",
subject: subject,
text: textbody
},
recipients: [{address: "myaddress#gmail.com"}]
};
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === 4) {
console.log(this.responseText);
}
});
xhr.open("POST", url);
xhr.setRequestHeader("content-type", "application/json");
xhr.setRequestHeader("accept", "application/json");
xhr.setRequestHeader("authorization", creds);
xhr.setRequestHeader("cache-control", "no-cache");
xhr.send(JSON.stringify(fetchbody));
}
Is there something wrong with my credentials setup here? Note that creds is set to my secret API key string.
Figured it out after chatting with the Sparkpost devs a bit - the service only allows "strict CORS" i.e. requests from server-side, and I was sending the request from client-side code.