I am trying to make a login authentication in angular, in which when we are entering email id and password we are getting a token. So for authentication, we have to send that header in the api get request but i am not able to do it.
My code is shown below
onSubmit(form:NgForm) {
this.http.post('https://pikreview.com/rest/user.php?f=authenticate',
JSON.stringify({
email: "a#gmail.com",
password: "12345"
})
).subscribe(res => {
localStorage.setItem('token', res.token);
var authToken = localStorage.getItem('token');
console.log("token is " + authToken);
var headers: HttpHeaders = new HttpHeaders({
'token': `${authToken}`,
'Access-Control-Allow-Credentials': true,
});
var req = new HttpRequest('GET',
'https://www.pikreview.com/rest/user.php', {
headers: headers,
withCredentials: true
}
);
this.http.request(req).subscribe(data => {
console.log(data);
})
}, error => {
console.log("something went wrong");
});
}
And one thing i have seen that whenever i pass token header there is something set-cookie generated which has token value on authentication page but on profile page it is not getting the same token and i think therefore it is showing invalid token.So,if anyone knows something about it and can solve my problem,please reply as soon as possible.
You just simple call the api with ur custom header, use HttpHeaders like this:
const httpOptions = {
headers: new HttpHeaders({
'Authorization': "YOUR_TOKEN"
})
}
this.http.get('http://localhost:5000/getUser',httpOptions)
Related
I have the following function working from an Angular component (in an Electron application) using HttpClient:
var auth = "Bearer" + "abdedede";
let header = new HttpHeaders({ "Content-Type": 'application/json', "Authorization": auth});
const requestOptions = {headers: header};
const url = 'https://reqres.in/api/users?page=1';
this.http.get<any>(url, requestOptions).toPromise()
.then(response=> {
//...
alert(JSON.stringify(response));
});
}
Now, here is a call from the electron side which calls the same endpoint but without the Authorization and Content-Type in the header:
let buffers:any = [];
const { net } = require('electron')
const request = net.request({
method: 'GET',
url: 'https://reqres.in/api/users?page=1'})
request.on('response', (response) => {
console.log(`HEADERS: ${JSON.stringify(response.headers)}`)
response.on('data', (chunk) => {
buffers.push(chunk);
})
response.on('end', () => {
let responseBodyBuffer = Buffer.concat(buffers);
let responseBodyJSON = responseBodyBuffer.toString();
responseBodyJSON = responseBodyJSON;
})
})
request.end()
(This latter function is thanks to a poster replying here: In an Electron Application I am successfully making an HTTP GET request from an Angular component. How can I do the same thing from the Electron side?)
My question is, could anybody please advise\show me how to add in the Authorization and Content-Type Header info to this call so that it replicates what the Angular version does - i.e. by passing the requestOptions data in the GET call?
Thanks.
I have found it. I needed to add:
request.setHeader("content-type", "application/json"); request.setHeader("Authorization", auth);
before I call:
request.on('response', (response) => {
I'm trying to receive an access token from the Zoom api via Oauth. No matter what form I try and send the body as, 'Content-Type': 'application/json' or Content-Type:application/x-www-form-urlencoded, it always errors to { reason: 'Missing grant type', error: 'invalid_request' }.
var options = {
method: "POST",
url: "https://zoom.us/oauth/token",
body: JSON.stringify({
grant_type: "authorization_code",
code: process.env.AUTH_CODE,
}),
redirect_uri: "https://zoom.us",
};
var header = {
headers: {
Authorization:
"Basic " +
Buffer.from(process.env.ID + ":" + process.env.SECRET).toString("base64"),
},
"Content-Type": "application/json",
};
var tokCall = () =>
axios
.post("https://zoom.us/oauth/token", options, header)
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error.response);
});
tokCall();
I'm fairly certain the answer lies in either the data type in which Oauth is receiving the data, or where/if it's receiving the body at all. Any suggestions would be gratefully received.
The error is being thrown because you're sending the data as the body of the post request when the Request Access Token Zoom API is expecting to find them as query parameters which you might know as query strings.
Reference
https://marketplace.zoom.us/docs/guides/auth/oauth#local-test
Image of page from link to highlight the use of query parameters and content-type requirement for API call
Change
var options = {
method: "POST",
url: "https://zoom.us/oauth/token",
body: JSON.stringify({
grant_type: "authorization_code",
code: process.env.AUTH_CODE,
}),
redirect_uri: "https://zoom.us",
};
to
var options = {
method: "POST",
url: "https://zoom.us/oauth/token",
params: {
grant_type: "authorization_code",
code: process.env.AUTH_CODE,
redirect_uri: "<must match redirect uri used during the app setup on zoom>"
},
};
The Content-Type header should be set to application/x-www-form-urlencoded as this is a requirement of the zoom API itself.
BTW, axios requires you to name the body field/object of your request as data and also there's no need for JSON.stringify() method since axios does that for you under-the-hood
Though it's a late answer, I'd like to share it since it took me some time to complete this using Axios.
So to make Zoom authorization, you need to do:
Base64 encode the secret and client id
const base64EncodedBody =
Buffer.from(`${ZOOM_CLIENT_ID}:${ZOOM_CLIENT_SECRET}`).toString('base64');
URI encode the grant_type, code and redirect_uri
const data =
encodeURI(`grant_type=authorization_code&code=${code}&redirect_uri=${redirectUri}`);
Send the request
const response = await axios.post('https://zoom.us/oauth/token', data, {
headers: {
Authorization: `Basic ${base64EncodedBody}`,
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(data),
},
});
When i send POST request form POSTMAN and get correct response
This is Form-Data Body request of Postman POST.
ENDPOINT : https://cholas.in/wp-json/digits/v1/send_otp
When i send POST request from POSTMAN and get Wrong response
JSON Body request
Content-Type : multipart/form-data;
Content-Type : multipart/form-data; header with json body :
Angular and IONIC code when i send post request
const formData = new FormData();
let httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'multipart/form-data; charset=UTF-8'
})
};
formData.append('countrycode',this.formSMS.countrycode);
formData.append('mobileNo',this.formSMS.mobileNo);
formData.append('type',this.formSMS.type);
formData.append('whatsapp',this.formSMS.whatsapp);
// rest data to the form.
//Object.keys(restObj).forEach(key => {
// formData.append(key, restObj[key]);
//});
console.log(formData);
// Send it.
return this.http.post(Url, formData, httpOptions)
.toPromise()
.catch((e) => {
console.log(e);
// handle me
});
But i get Wrong Response that i don't want.
NB: OTP Providers Documentation NOTE: The request should be sent as POST Parameters in Body
What will be the right wey in IONIC/ANGULAR/POSTMAN(JSON Type) to getting right Resonse that i getting as POSTMAN first Screenshot ?
You dont need to pass httpOptions in post data since You are passsing Form data angular will handle that for you
const formData = new FormData();
let httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'multipart/form-data; charset=UTF-8'
})
};
formData.append('countrycode',this.formSMS.countrycode);
formData.append('mobileNo',this.formSMS.mobileNo);
formData.append('type',this.formSMS.type);
formData.append('whatsapp',this.formSMS.whatsapp);
// rest data to the form.
//Object.keys(restObj).forEach(key => {
// formData.append(key, restObj[key]);
//});
console.log(formData);
// Send it.
return this.http.post(Url, formData)
.toPromise()
.catch((e) => {
console.log(e);
// handle me
});
Below stackbliz contains the solution please refer
https://stackblitz.com/edit/angular-http-get-examples-f28x9u?file=app%2Fapp.component.ts
I'm looking at connecting to an https web api, I've obtained my token, and my username by receiving an email about it, and there isn't really any sample code to connect to the webservice using node; however there are examples for Java and C#, and based on those this is what I came up with...
/* WEB API: https://www.careeronestop.org/Developers/WebAPI/technical-information.aspx?frd=true */
// UserID: ...
// Token Key: ...==
// Your agreement will expire three years from today on 12/8/2019 and all Web API services will be discontinued,
// unless you renew.
var https = require('https');
var username = '...';
var tokenKey = "...==";
var options = {
host: 'api.careeronestop.org',
port: 443,
path: '/v1/jobsearch/' + username + '/Computer%20Programmer/15904/200/2',
method: 'GET',
headers: {
'Content-Type' : 'application/json',
'Authorization' : '' + new Buffer(tokenKey.toString('base64'))
}
};
var req = https.request(options, function(res) {
console.log(res.statusCode);
res.on('data', function(d) {
process.stdout.write(d);
});
});
req.end();
req.on('error', function(e) {
console.error(e);
});
Unfortunately however, it returns a 401 Unauthorized, so is there anything that needs added to this to get it working? Some headers maybe?
I used this form to submit a request and then looked in the Chrome debugger network tab to see exactly what request was sent.
The authorization header is supposed to look like this:
Authorization: Bearer 901287340912874309123784
You also want this:
Accept: application/json
So, assuming tokenKey is already a string since it appears to have been sent to you in an email, you can change your code to this:
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer ' + tokenKey
}
I have error meantime angular2 post rest data to NodeJS backend.
I see POST is done, server is LOG correct data, but error is showing up on browser.
An error occurred:
SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data
My NG2 call and service:
onSubmit(form:FormGroup) {
let userform: FormGroup = form.value;
console.log("userform: ", userform);
if (form.valid) {
console.log(form.value);
this.appService.signIn(userform)
.subscribe(form => console.log('subscribe: ', form))
} else {
console.log("Form is not VALID!");
}
}
SERVICE:
signIn(dataUser: Object): Observable<User> {
dataUser = JSON.stringify(dataUser);
debugger;
let headers = new Headers({
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': 'http://127.0.0.1:3005'
});
let options = new RequestOptions({ headers: headers });
console.log("data: ", dataUser, "\nHeaders: ", headers);
return this.http
.post( this.signInUrl, dataUser, options)
.map( (res:Response) => res.json().data || { } as User )
.catch(this.handleError);
}
and nodeJS:
app.post('/login', function (req, res) {
console.log("Recived login request!");
console.log("Request: ", req.body);
res.header({
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET,PUT,POST,DELETE',
'Accept': 'q=0.8;application/json;q=0.9'
})
res.end();
});
In post we have: "{"username":"username","password":"password"}".
What I'am making wrong? Please for help or solution.
Awwwww. That was my bad, Take care of your NodeJS Server response. After get POST, should be sended any res.json({status: "OK"}) or sommething similar, to get response. This error was not because of Angular2, but because of NodeJS. Browser get empty response from nodeJS, or it was not JSON format.