Why can I not authenticate with the GitHub REST API using Axios? - javascript

I'm sort of new to REST..
For full disclosure, I'm running this code inside of a Netlify Lambda function and testing via netlify-lambda.
My curl command works:
curl -u "<username>:<password>" https://api.github.com/repos/<username>/<reponame>
But when I attempt a get request via axios I'm getting a 404 (which according to github docs implies an auth issue). This is what I'm doing (also doesn't work without the custom headers, I've just been trying random things).
axios({
method: "get",
url: `https://api.github.com/repos/${user}/<reponame>/`,
headers: {
Authorization: `Bearer ${githubToken}`,
"Content-Type": "application/json"
},
auth: {
username: user,
password: pass
}
})
.then(res => {
callback(null, {
statusCode: 200,
body: JSON.stringify(res.data)
});
})
.catch(err => {
callback(err);
});
One thing I noticed was that it seems axios was taking my username and password and prepending them to the url i.g. https://<username>:<password>#api.github.com/repos/<username>/<reponame>
Is this how auth should be sent over?

I shouldn't have had a trailing forward slash at the end of my URL.

If you already have a token you don’t need user/pass, just add the token to the header.

Related

Determine if a link is http of https from a string that does not contain the full url

I have an input string that contains a partial URL such as "wikipedia.org" and I want to get the full URL "https://www.wikipedia.org/" using Node or JavaScript.
Is there a standard way to do this?
The problem is not knowing if the URL is HTTP or https and I would rather not make two API calls to test each case.
That problem can be solved by calling a specific API that provides SSL Verify checks.
As an example you can use rapidapi.
const axios = require("axios");
const options = {
method: 'POST',
url: 'https://ssl-certificate-checker.p.rapidapi.com/ssl-certificate',
headers: {
'content-type': 'application/json',
'X-RapidAPI-Key': '9a02e1bd8emsh83423276ecdc759p153572jsn874d28bed296',
'X-RapidAPI-Host': 'ssl-certificate-checker.p.rapidapi.com'
},
data: '{"port":"443","url":"wikipedia.org"}'
};
axios.request(options).then(function (response) {
console.log(response.data);
}).catch(function (error) {
console.error(error);
});
For details you can check the site of the API.
Click here to check articles and solutions to similar questions.

Auth0 returning 401 unauthorized when requesting new auth token

I am trying to request an authorization token through auth0 using an M2M application with the code:
var axios = require("axios").default;
var options = {
method: 'POST',
url: 'https://chaptify.us.auth0.com/oauth/token',
headers: { 'content-type': 'application/x-www-form-urlencoded' },
data: {
grant_type: 'client_credentials',
client_id: 'KbFUk08Qq24VA03i1mVAkLc3uPKc6V79',
client_secret: process.env.AUTH0_M2M_CLIENT_SECRET,
audience: process.env.AUTH0_AUDIENCE
}
};
axios.request(options).then(function(response) {
console.log(response.data);
}).catch(function(error) {
console.error(error);
});
which is pulled straight from auth0's website. but every time I've gotten a 401 error so far I've tried
using different M2M applications
making sure all the M2M applications are authorized and trying again
checking the Token Endpoint Authentication Method is set to None
checking all the fields are correct
googling to see if I can find absolutely anything to help
pasting in the values directly
unauthorizing the M2M shutting down the application, waiting a while then starting it up again, nothing

React fetch post, page refreshing and becomes a GET request

I have a login page in my REACT website sending a POST request with fetch, but every time the request is submitted for some reason it refreshes the page and send it as a GET request, here's the method on my login page:
onSubmitSignIn = () => {
fetch("http://192.168.56.1:8560/signin", {
type: 'POST',
headers: {'Accept': 'application/json',
'Content-Type': 'application/json'},
body: JSON.stringify({
email: this.state.signinEmail,
password: this.state.signinPassword,
}),
})
.then(response => response.json())
.then(data => {
if (data ==='success'){
}
})
}
the server side signing page is as follows:
app.post('/signin', (req, res) => {
if (req.body.email === database.users[0].email && req.body.password === database.users[0].password){
res.json("success");
}else{
res.status(404).json("Error loggingin");
}
})
It's working fine with Postman, the server seems to be ok.
I have tried changing HTTP to https even though my server is HTTP just in case.
Tried restarting both servers, tried changing to fetch to axios but nothing seems to be working.
Any thoughts?
onSubmitSignIn = (event) => {
event.preventDefault() // <= You Need this
fetch("http://192.168.56.1:8560/signin", {
type: 'POST',
headers: {'Accept': 'application/json',
'Content-Type': 'application/json'},
body: JSON.stringify({
email: this.state.signinEmail,
password: this.state.signinPassword,
}),
})
.then(response => response.json())
.then(data => {
if (data ==='success'){
}
})
}
Create-React-App Proxying API Requests in Development -- src/setupProxy.js
People often serve the front-end React app from the same host and port as their backend implementation.
Such setup is not required. However, if you do have a setup like this, it is convenient to write requests like fetch('/api/todos') without worrying about redirecting them to another host or port during development.
To tell the development server to proxy any unknown requests to your API server in development, add a proxy field to your package.json, for example:
"proxy": "http://localhost:8560",
Configuring the Proxy Manually
First, install http-proxy-middleware using npm or Yarn:
$ npm install http-proxy-middleware --save
$ # or
$ yarn add http-proxy-middleware
Next, create src/setupProxy.js and place the following contents in it:
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function(app) {
app.use(
'/api',
createProxyMiddleware({
target: 'http://localhost:8560',
changeOrigin: true,
})
);
};
API:
https://create-react-app.dev/docs/proxying-api-requests-in-development/
I'm just replying in case anybody has got the same issue as I was having, after a couple of sleepless nights digging through my code, I figure the template for my login page was taken from a "tachyon" template, what I missed, somewhere in my version control, was a "form" that was actually supposed to be turned into a "div", after going through this question here why-the-post-request-becomes-a-get-request it hit me, basically, if you happen to be taking the information from inside of a "form" and this form does not have a method post, it will automatically turn the API request into a GET request and fill up the URL with the information.
So that is sorted. Now let us tackle the rest of the bugs.

Javascript REST API with body in GET

I'm working in Javascript (frontend) and have a colleague working in the backend with NodeJS.
When calling a GET request, he asks me to put the data in the body, but I could not figure out how to do that. (If I use this code to a POST request, it works fine).
Could you tell me if this is possible and how to do it? He says that it is possible, but I've googled a lot and could not find the correct way to do that.
ERROR that I get: "Failed to execute 'fetch' on 'Window': Request with GET/HEAD method cannot have body."
let URL = "http://localhost:3000/verifyUser";
let token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI2NjJDMTRBNk";
fetch(URL, {
method: request,
mode: 'cors',
body: JSON.stringify({
user: 'Carlos6',
password: '543534543',
email: "algo6#gmail.com"
}),
headers: {
'Accept' : 'application/json',
'Content-type': 'application/json; charset=UTF-8',
'auth-token': token
}
}).then(function (response) {
if (response.ok) {
return response.json();
}
return Promise.reject(response);
}).then(function (data) {
console.log(data);
}).catch(function (error) {
console.warn('Something went wrong.', error);
});
You are using HTTP GET and sending a body.
If you want to send a body (JSON) you should use the PUT and POST.
The best will probably be to:
change your client code to method: "PUT"
change the server to access PUT request
If you want to know which one to chose look at this question:
( PUT vs. POST in REST)
If you wish to send a request with a body then you should make a POST-request and not a GET one. GET-request cannot have a body by its nature and primary goal.
All params of GET-request must be indicated in the URL itself only.

Discord guilds.join resulting in Bad Request

I am trying to add a member to my guild using Node's request module.
The access token is retrieved through Discord's OAuth2 system. The token provides identify and guilds.join permissions.
The bot token has been copied directly from Discord's development site. The bot is connected to my application, joined the guild I am working with and has permission for both manage roles and create instant invites.
Here is my request,
request({
url: `http://discordapp.com/api/guilds/${guildID}/members/${userID}`,
method: "PUT",
headers: {
'Authorization': `Bot ${botToken}`,
'Content-Type': 'application/json'
},
json: {
'access_token': access_token
}
}, (err, res, body) => {
console.log(body);
});
and here is the response
{ _misc: [ 'Expected "Content-Type" header to be one of {\'application/json\'}.' ] }
I have searched through all related questions on here and cannot find the solution.
Any help would be valued. Thanks.
I figured out the solution. You'll want to take advantage of DiscordJS and use the guild.addMember function rather than building your own request.

Categories

Resources