Cannot get post working in Angular2 - node.js

So i'm trying to authenticate in my angular application. I attended headers and created an stringified body. I also looked at serveral other forum post about sending post requests in postman but i cannot get it working.
getToken()
{
console.log('started getting of token');
//get username and password from local storage
//Send username and password via body
let headers = new Headers();
let body = JSON.stringify({
name: 'test',
password: 'test'
});
headers.append('Content-Type', 'application/x-www-form-urlencoded');
this.jwt = this.http.post('http://localhost:8080/api/authenticate/', {
headers: headers,
body: body
}).map(res => res.text()).subscribe(data => console.log(data));
}
So above is my code. I know it might be a little silly thing but I cannot get it working.
I get the error that the user cannot be found. That happens when the username is wrong, and when the username does not exsist in the database. So that a little extra tricky as well.
Who knows what the stupid mistake is that I made?

Add this code in your service.ts file.
import { Http, URLSearchParams} from '#angular/http';
getToken()
{
let headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
let body = new URLSearchParams();
body.set('name', test);
body.set('password', test);
return this.http.post("http://localhost:8080/api/authenticate/", body, headers).map(response => response.json());
}

Use following code to send post request
this.jwt = this.http.post('http://localhost:8080/api/authenticate/',body,headers).map(res => res.text()).subscribe(data => console.log(data));

This code is what I use for post request
send_request_post(url: String, data:{})
{
var headerPost = new Headers
({
'Content-Type' : 'application/json ;charset=utf-8'
})
return this.http.post(url, JSON.stringify(data), {headers: headerPost})
.toPromise()
.then
(
response =>
{
console.log(response);
}
)
}

Related

forward the response of http request to the client

I am invoking a web service through an azure function in node.js with Axios, I have a couple of questions here.
1- in the body of this request I'm hardcoding the value for appUser. however, if I want to run this request on postman and pass the JSON value in the body for appUserwhat changes do I need to do in the code so the param value can pick up what is being passed.
2- the response for this request is only returned in the console of the editor but not getting sent to the client response body (i.e. postman) any idea how to forward the response?
module.exports = async function () {
const axios = require("axios");
const data = {
appUser: "yamen",
};
const headers = {
Authorization:
"Basic WUFNkVQRDg9",
};
{
axios
.post(
"https://tegossl/GetAppUser?company=Enva",
data,
{ headers: headers }
)
.then((response) => {
console.log(`Status: ${response.status}`);
console.log("data: ", response.data);
})
.catch((err) => {
console.error(err);
});
}
};

Nodejs - Axios not using Cookie for post request

I'm struggling with AXIOS: it seems that my post request is not using my Cookie.
First of all, I'm creating an Axios Instance as following:
const api = axios.create({
baseURL: 'http://mylocalserver:myport/api/',
header: {
'Content-type' : 'application/json',
},
withCredentials: true,
responseType: 'json'
});
The API I'm trying to interact with is requiring a password, thus I'm defining a variable containing my password:
const password = 'mybeautifulpassword';
First, I need to post a request to create a session, and get the cookie:
const createSession = async() => {
const response = await api.post('session', { password: password});
return response.headers['set-cookie'];
}
Now, by using the returned cookie (stored in cookieAuth variable), I can interact with the API.
I know there is an endpoint allowing me to retrieve informations:
const readInfo = async(cookieAuth) => {
return await api.get('endpoint/a', {
headers: {
Cookie: cookieAuth,
}
})
}
This is working properly.
It's another story when I want to launch a post request.
const createInfo = async(cookieAuth, infoName) => {
try {
const data = JSON.stringify({
name: infoName
})
return await api.post('endpoint/a', {
headers: {
Cookie: cookieAuth,
},
data: data,
})
} catch (error) {
console.log(error);
}
};
When I launch the createInfo method, I got a 401 status (Unauthorized). It looks like Axios is not using my cookieAuth for the post request...
If I'm using Postman to make the same request, it works...
What am I doing wrong in this code? Thanks a lot for your help
I finally found my mistake.
As written in the Axios Doc ( https://axios-http.com/docs/instance )
The specified config will be merged with the instance config.
after creating the instance, I must follow the following structure to perform a post requests:
axios#post(url[, data[, config]])
My requests is working now :
await api.post('endpoint/a', {data: data}, {
headers: {
'Cookie': cookiesAuth
}
});

Getting LinkedIn access token through http request on node.js server

I am following the Authorization Code Flow (3-legged OAuth) documentation and I am now at step 3 where I need to use the authorization code in order to recieve an access token from LinkedIn. In the project I am using node.js, typescript and the node-fetch library. The following function creates a body with content type x-www--form-urlencoded since this is content type which LinkedIn require.
async function GetAccessToken(data: any) {
let body: string | Array<string> = new Array<string>();
for (let property in data) {
let encodedKey = encodeURIComponent(property);
let encodedValue = encodeURIComponent(data[property]);
body.push(encodedKey + "=" + encodedValue);
}
body = body.join("&");
const response = await fetch("https://www.linkedin.com/oauth/v2/accessToken", {
method: 'POST',
headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},
body: body
}).then((res: any) => {
console.log("Result", res);
});
return response;
}
I do not recieve any errors and the response status is 200 but the response values I recieve are:
size: 0,
timeout: 0,
and what LinkedIn promise is:
access_token
expires_in
When I post the url with my parameters using postman the request goes through and I recieve the correct data which indicates the problem lies within my request function and not my values.
Any help is appreciated!
You need add all headers from postman
const urlencoded = new URLSearchParams();
urlencoded.append("client_id", env.LINKEDIN_CLIENT_ID);
urlencoded.append("client_secret",env.LINKEDIN_CLIENT_SECRET);
urlencoded.append("grant_type", "authorization_code");
urlencoded.append("code", code);
urlencoded.append(
"redirect_uri",
"http://localhost:3000/api/auth/linkedin-custom"
);
const accessTokenPromise = await fetch(
"https://www.linkedin.com/oauth/v2/accessToken",
{
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
body: urlencoded,
}
);

New to Typescript & Angular problems with Http Post

I'm new to Angular and Typescript and I try to create a simple login page. I've created a service in typescript which is invoked when the user presses the 'Login' button. The textboxes which contains the username and password is bound correctly to the model, but when I send the request to my backend written in C#, it will not hit the breakpoint which I suspect is because of the format of the message being sent on the wire.
So using PostMan, I'm able to invoke the service and get back an access_token When exporting the request to code in PostMan this is what the NodeJS variant look like:
var request = require("request");
var options = { method: 'POST',
url: 'http://localhost:8081/login',
headers:
{ 'postman-token': '34dd4d0f-ff16-db4f-ebae-dab945729410',
'cache-control': 'no-cache',
'content-type': 'application/x-www-form-urlencoded' },
form: { username: 'test', password: 'test', grant_type: 'password' } };
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});
And this is my Typescript code
login(userName: string, password:string) : Observable<boolean> {
var headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded')
var content = JSON.stringify({
username: userName,
password: password,
grant_type: this.grant_type
});
return this.http.post(this.authenticationEndpoint, content, {headers: headers})
.map((response:Response) => {
let token = response.json() && response.json().token;
if(token){
//this.token = token;
localStorage.setItem('user', JSON.stringify({userName: userName, token:token}));
return true;
}
return false;
});
}
This results in an error in Visual Studio Code, which says:
I'm not really sure how I should interpret this error message, but since the method in my webservice is not invoked I'm pretty sure that it has something to do with the HTTP headers or the format of the Http Post.. Any ideas?
Using URLSearchParams as the body of the request and angular will automatically set the content type to application/x-www-form-urlencoded
import { URLSearchParams } from "#angular/http"
let body = new URLSearchParams();
body.set('username', username);
body.set('password', password);
.....
this.http.post(this.authenticationEndpoint, body).map(..)

Data is been sent from client but not reached in server angular2 and nodejs

I am trying to post my form data to server(node) but it is not getting reached there when i put console to data in backend it says undefined.Data is been sent from client but not reached in server.I think i am wrong at headers,can any one please suggest help.
my ts,
var headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded')
this.http.post(this.header1+'login', JSON.stringify(form), { headers: headers })
my server,
exports.login = function( req, res ) {
console.log("Params:"+req.body.email);
//console.log('email:'+params.email);
var query = 'select * from profile where email = ? and password = ?';
connection.query(query,[req.body.email,req.body.password],function(error,result,rows,fields){
if(!!error){console.log(error)
console.log('fail');
}else{
console.log(result);
res.send(result);
}
// }
});}
my routes(express)
router.post('/login', admin.login);
http uses Observable and observables are lazy. They don't actually execute anything unless subscribed to.
You need either
this.http.post(this.header1+'login', JSON.stringify(form), { headers: headers })
.subscribe(response => console.log(response.json());
this.http.post(this.header1+'login', JSON.stringify(form), { headers: headers })
.toPromise();
to make http send the request.

Resources