How to pass data from angular to node js server? - node.js

My app.component.ts contains
login() {
var user = `{ email: ${this.email}, password: ${this.password} }`
const headers = new HttpHeaders()
.set('Authorization', 'my-auth-token')
.set('Content-Type', 'application/json');
this.http.post('http://localhost:3000/signin', user, {
headers: headers
}).subscribe(data => {
});
console.log(`email: ${this.email} password: ${this.password}`)
}
When trying to get the data in node I get
error: SyntaxError: Unexpected token e in JSON at position 2
I am using
req.body
to get the data.
What is the correct way to parse the JSON data? Also wanted to know if this is the correct way to pass form data from angular to node?

var user = {
email: this.email,
password: this.password
}
...
this.http.post('http://localhost:3000/signin',user).subscribe(...)

With Angular 6 HttpClient, you don't need to stringify your object (see POST example from official doc). In the same way, for a GET request, HttpClient parse json data for you.
Try this :
login() {
const user = { email: this.email, password: this.password };
const headers = new HttpHeaders({
'Authorization': 'my-auth-token',
'Content-Type': 'application/json'
});
this.http.post('http://localhost:3000/signin', user, {
headers: headers
}).subscribe(data => {});
console.log(`email: ${this.email} password: ${this.password}`) }

user= {
email: aka#gmail.com,
password: 123,
}
$http({
method: "POST",
url: http://localhost:3000/signin,
data: JSON.stringify(user),
headers: headers
}).success(function(data) {
// you can print data hera
}
}).error(function() {
});

First i thought you using an object for the user, than a saw it's a string.
Your data is not with correct json format.
Try to put quotes on the fields name
var user = `{ "email": ${this.email}, "password": ${this.password} }`
WRONG!
You should stringify the data - JSON.stringify(user)
this.http.post('http://localhost:3000/signin', JSON.stringify(user), {
headers: headers
}).subscribe(data => {
});

Related

MailChimp: set Language with nodejs SDK

I'm trying to set a suscriber's Language with MailChimp nodejs SDK while adding him/her to a list.
The nodejs SDK calls the API https://us2.api.mailchimp.com/3.0/lists/<list-ID>/members, and it successfully creates a new member. However, it doesn't set the user's language. I read online that I have to pass the Accept-Language header with my HTTP request, so it is what I did.
In order to be able to add a custom header using the SDK, I slightly edited the SDK to add a defaultHeaders option. With this modification, the header is correctly set, but unfortunately it doesn't change anything: the new member still doesn't have the language set.
Here is my code:
import mailchimp from "#mailchimp/mailchimp_marketing";
export const handler = async(event) => {
const params = JSON.parse(event.body);
mailchimp.setConfig({
apiKey: process.env.apiKey,
server: process.env.server,
defaultHeaders: {
'Accept-Language': event.headers['accept-language'],
},
});
const email = params.email;
const firstname = params.name.substring(0, params.name.indexOf(' ')) || "";
const lastname = params.name.substring(params.name.indexOf(' ') + 1) || "";
return await mailchimp.lists.addListMember(process.env.listId,
{
email_address: email,
status: 'subscribed',
email_type: 'html',
merge_fields: {
FNAME: firstname,
LNAME: lastname,
},
}
);
};
The generated request is the following:
Request {
method: 'POST',
url: 'https://us2.api.mailchimp.com/3.0/lists/<list-ID>/members',
header: {
'User-Agent': 'node-superagent/3.8.1',
Authorization: 'Basic XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX=',
'Accept-Language': 'fr-FR,fr;q=0.9,en-US;q=0.8,en;q=0.7',
'Content-Type': 'application/json',
Accept: 'application/json'
},
writable: true,
cookies: '',
qs: {},
qsRaw: [],
data: {
email_address: '<the-tested-email-address>',
status: 'subscribed',
email_type: 'html',
merge_fields: { FNAME: 'Firstname', LNAME: 'Lastname' }
},
}
Still, the created member doesn't have the language set.
Please help me, it would really be appreciated 🙏
How can I set a new member's language when creating it using MailChimp API?

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
}
});

node-fetch send post request with body as x-www-form-urlencoded

i want to send a post request using node-fetch with a body payload encoded in the x-www-form. I tried this code but unfortunately it doesnt work:
paypalSignIn = function(){
var username = process.env.PAYPALID;
var password = process.env.PAYPALSECRET;
var authContent = 'Basic '+base64.encode(username + ":" + password);
fetch('https://api.sandbox.paypal.com/v1/oauth2/token', { method: 'POST',
headers: {
'Accept': 'application/json',
'Accept-Language' :"en_US",
'Authorization': authContent,
'Content-Type': 'application/x-www-form-urlencoded'
},
body: 'grant_type=client_credentials' })
.then(res => res.json()) // expecting a json response
.then(json => console.log(json));
}
I'm not sure if this way is possible but i need to use this standard for die paypal api.
I'm getting statu code 400 with error
grant_type is null
Thx
I don't know if this is the only error, but at the very least you need a space between the word Basic and the encoded username/password.
Next time you ask a question, also post what your script returned. I'm guessing it was a 401 error in this case.
I used the PayPal sandbox today, here is how I managed to get my access token and a successful response (and also answering the OP's question about sending application/x-www-form-urlencoded POST requests with data) =>
I did it with node-fetch but the plain fetch API should work the same.
import fetch from "node-fetch";
export interface PayPalBusinessAccessTokenResponseInterface {
access_token: string;
}
export interface PayPalClientInterface {
getBusinessAccessToken: (
clientId: string,
clientSecret: string
) => Promise<PayPalBusinessAccessTokenResponseInterface>
}
const paypalClient: PayPalClientInterface = {
async getBusinessAccessToken(
clientId: string,
clientSecret: string
): Promise<PayPalBusinessAccessTokenResponseInterface> {
const params = new URLSearchParams();
params.append("grant_type", "client_credentials");
const paypalAPICall = await fetch(
"https://api-m.sandbox.paypal.com/v1/oauth2/token",
{
method: "POST",
body: params,
headers: {
"Authorization": `Basic ${Buffer.from(clientId + ":" + clientSecret).toString('base64')}`
}
}
);
const paypalAPIRes = await paypalAPICall.json();
return paypalAPIRes;
}
};
export default paypalClient;

How can I use state to make a POST fetch request on my backend

I'm working on my first app right now which I created in react native for the front end and using Node JS as a backend and mongodb for the database.
I'm trying to implement register form for my user but I don't really know how to do this with the state because it keeps saying cannot evaluation this.state.name.
What I want to do is a POST request using fetch api to register an account it works using Postman so the error come from my front end.
So what I do is I create my function to do that but I want the body to represent the value the user typed in the different field which I store in the state when you'll see the code it will be clear.
If I use the state it does not work however if I put some value directly in my function it works.
This first thing is my function with the fetch API if I do this it does not work, below is how I get the state of each field (see the )
clickthebutton = () =>{
//var data = this.state
fetch('http://localhost:5050/api/new/register',{
method:'POST',
headers : {'Content-Type': 'application/json'},
body : {
name:this.state.name,
age:this.state.age,
password:this.state.password,
email:this.state.email
},
})
}
<Input
label="Your email address"
placeholder="yo#gmail.com"
onChangeText={(text)=> this.setState({email:text})}
value={this.state.email}
>
My state looks like this :
this.state={
email:null,
password:null,
name:null,
age:null,
dataImage:null
}
I would like to send the body, if I do body : this.state it does not send anything when I do a console.log(req.body) on my server it shows an empty object.
Thanks for any help
EDIT : Problem fixed, my function was not referring to my class.
First of all you need a correct element for your email and password inputs, for example (for email):
<TextInput
value={this.state.name}
keyboardType={'email-address'}
placeholder="Your email address"
onChangeText={text => this._onEmailChange(text)}
/>
you also need a function to update the name value (you will need a similar function to update any value coming from a TextInput element)
_onEmailChange = text => {
this.setState({ name: text });
};
Then you can prepare your request as follow
fetch('http://localhost:5050/api/new/register', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
email: this.state.name,
password: this.state.password
...
}),
})
.then(response => response.json())
.then(responseJson => {
// do what you want with the response here
})
.catch(error => {
console.error(error);
});
You have specified in the header that you send in json format when you send. When sending to the server, you must convert to jsonString.
fetch('http://localhost:5050/api/new/register', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
name:this.state.name,
age:this.state.age,
password:this.state.password,
email:this.state.email
}),
});
Ok You can try use Formdata
let formdata = new FormData();
formdata.append("name", this.state.name);
formdata.append("age", this.state.age);
formdata.append("password", this.state.password);
formdata.append("email", this.state.email);
fetch('http://localhost:5050/api/new/register', {
method: 'POST',
headers: {
"Content-Type": "multipart/form-data"
},
body: formdata
})
.then(res => res.json())
.then(reponse => {
console.log(reponse)
})
.catch(error => {
console.error(error);
});
After getting all form-data in your state you have two options to make a request to backend.
Either set Content-Type As application/text or remove header.
fetch('http://localhost:5050/api/new/register',{
method:'POST',
headers : {'Content-Type': 'application/text'},
body : {
name:this.state.name,
age:this.state.age,
password:this.state.password,
email:this.state.email
},
})

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(..)

Resources