Angular2. HTTP.POST doesn't work - node.js

this is my HTTP service right here :
postData(name, country) {
var body = JSON.stringify({
"name":name,
"country":country
});
console.log(name); // it outpus the correct value
console.log(country); // it outpus the correct value
return this.http.post('http://178.62.58.150:5000/api/cosmo/',body)
.map(res => {
res.text();
console.log(res.text());
})
.do(data => {
this.data = data;
// console.log(this.data);
})
}
It seems that it doesn't send the body to the POST request.
these output the correct value of the body
console.log(name);
console.log(country);
But
console.log(res.text());
It gives me a DB validation Error, which states that the body and country are required...
How do I send the body correctly?
P.S. : I tested this with POSTMAN and it works!

Looks like the issue is in building the post params, try
var body = JSON.stringify({
name: name,
country: country
})
Note that my hash keys are not strings, because stringify will convert a JavaScript object to a JSON string.
If this doesn't work, check with Google Developer tool on what your request is sending to the server.

I have added
let headers = new Headers();
headers.append("Content-Type","application/json");
return this.http.post('http://178.62.58.150:5000/api/cosmo/',body,{headers:headers})

Related

Sending data from react to node by get request using axios library

for more than 3 hours I'm handling with an issue, what I'm trying to do is sending a get request from react to nodejs using axios library, I wanna pass some data into this request, as we know the get request don't have a body, so I've sent the data as query parameter like that
// base URL
const url = "http://localhost:8080/loginAsTeacher";
if(loginAs === "loginTeacher"){
axios.get(url,{
params :{
email: "abc123#gmail.com",
password: "abc1234*"
}
})
.then(res => console.log(res)) // this line return status:200 and data:null
.catch(err => console.log(err.message))
}
so this request success but the problem is the email and password are not passing to the backend
router.get("/loginAsTeacher", async (req,res)=>{
// values coming from the client
const loginEmail = req.params.email;
const loginPassword = req.params.password;
console.log(req.params); // this line return {} empty object
// get data of that user by his/her mail
const teacherData = await myModel.findOne({
email: loginEmail
}).exec()
res.status(200).json({
status: 200,
data: teacherData
})
})
the console.log above return an empty object, which means there's no parameters
Is this not the right solution ???
thanks for reading
To get your queries you need to get req.query instead of req.params
Btw. it's dangerous to send sensitive data over get. It could be get logged in plaintext even over https
use req.query instead of req.params. it will solve the issue

How to assign the response from Axios get to a variable and access it later

I am trying to create an integration for two websites using API's of both websites.
I created a rest API where both the software can send post and get request and my API will resolve it.
when software 1 makes a post request to my application at "/send_tests", my application needs to get the post request and send it to the 2nd software and return the data that I get from 2nd software to 1st software
What I am trying to do is, when I receive a post request at "/send_tests", I am then trying to read the req and then make a post request from my application to another application, and then when I receive the response from the post request I am trying to save it in a global variable and then responding back to the first post request that I got at "/send_tests". But when I try to save the response and try to access it later in the code, I am getting undefined for that variable
//My function to return the data
async function postData (first_name,last_name, email, URL, token) {
var data = {
"assessmentStatusWebHook": "http://localhost:3000/api/hook",
"notifyAssessmentAvailableUsingEmail": 1,
"firstName": first_name,
"lastName": last_name,
"email": email
}
axios.post(url, data, {headers: {'Accept': 'application/json'}})
.then((res) => {
console.log(`Status: ${res.status}`);
return res.data.assessmentId
}).catch((err) => {
console.error(err);
});
};
//My router to res.send the assessmentId that I get from postData
router.post("/send_tests", [
check('partner_test_id').exists(),
check('first_name').exists().isString(),
check('last_name').exists().isString(),
check('resume_url').optional(),
check('phone_number').optional().isString(),
check('email').exists().isEmail().normalizeEmail(),
check('url').exists().isString()], async (req, res) => {
let partner_test_id = req.body.partner_test_id;
let first_name = req.body.first_name;
let last_name = req.body.last_name;
let resume_url = req.body.resume_url;
let phone_number = req.body.phone_number;
let email = req.body.email;
let url = req.body.url;
// Send response
const errors = validationResult(req);
var assessmentId
(async () => {
try {
//I am trying to save the response from this post
assessmentId = await postData(first_name,last_name, email,jobTitle1)
}catch (err){
console.log ('Errorrrrrrr' + err)
}
})();
if (!errors.isEmpty()) {
return res.status(422).json({ errors: errors.array() });
}
console.log("In the function for assessmentID " + assessmentId)
res.send({
//I am trying to access the response from the previos post request "assessmentId"
"partner_interview_id":assessmentid
});
}); ```
I need to save the assessmentID and send it in the res.send as a response. Please Help
You can use async/await as axios returns the promise. You can do something like this:
async getData() {
const res = await axios.post(url, data, {headers: {'Accept': 'application/json'}});
return await res.json();
}
async function getPostedData (first_name,last_name, email, URL, token) {
var data = {
"assessmentStatusWebHook": "http://localhost:3000/api/hook",
"notifyAssessmentAvailableUsingEmail": 1,
"firstName": first_name,
"lastName": last_name,
"email": email
}
const results = await getData(); // use the results
return results;
};
//My router to res.send the response
router.post("/send_tests", [
....
....
You can check here for more details about axios with async/await.

Is it possible to redirect a post request after modifying the body in a Node (express) server?

I know that it is possible to redirect a post request to another url like so:
app.post((req, res) => {
res.redirect(307, 'https://something.com/api/test');
})
this will send the body also to something.com/api/test. What I want to do is:
app.post((req, res) => {
req.body.something = 'somevalue'; // this value is not added.
res.redirect(307, 'https://something.com/api/test');
})
Is it possible to modify the body and forward it to the redirect url?
Thank you for the help.
//Use query instead of body
const url = require('url')
app.post('/',(req,res)=>
{
res.redirect(url.format({
pathname:'/newUrl',
query: {
"email": req.body.email //assigning a value from the body
"theMissingValue" : "some-value" //manually assigning a value
}
}));
})
app.get('/newUrl',(req,res)=>
{
console.log(req.query.theMissingValue); //prints "some-value"
})

Sending Emails using a Lambda Function, NodeJS, Mailgun, and testing Params in Postman

I am learning all of this as I go. The goal is to simply send an email using variables, and here's the code that I have so far in test.js:
const mailgunSdk = require('mailgun-js');
const apiKey = 'MAILGUN_API_KEY';
const domain = 'MAILGUN_DOMAIN';
const mailgun = mailgunSdk({
apiKey,
domain
});
exports.handler = async(event, context, callback) => {
//console.log(event.body)
//const data = JSON.parse(event.body)
let response
try {
/* Send email to recicipent */
response = await mailgun.messages().send({
from: 'Reginald Fromington <mg#fromaddress.com>',
to: 'bobloblaw#gmail.com',
subject: 'Hello',
text: event.messageText
})
} catch (e) {
//console.log('Err', e)
return {
statusCode: e.statusCode || 500,
//body: JSON.parse({
// error: e.message
//})
}
}
return {
statusCode: 200,
body: JSON.stringify({
result: response.message
})
}
}
Using Postman, I can actually get a message in my inbox if I have text: as a string, such as text: 'Thank you for your email' if I'm running the function without any params. However, if I want to use a variable, I have no idea how to pass them into the function. I've tried text: event.messageText, text: response.messageText, text: mailgun.messageText, and every possible combination of variables that I could imagine to pull from.
Most of the documentation that I could find is outdated or doesn't address this issue. I also don't really know how to google this issue because again, I'm new to all of this.
Thanks,
-Andrew
Attempting to pass parameters into Lambda Function

Calling users from angular to node (MEAN) is sending only email and _id to angular

I'm using the following code ..
// Node.js
router.get('/users/all', authenticate, (req, res) => {
User.find({some query}).select('firstName lastName email').then((users) => {
res.send(users);
});
//Angular Service
let opts = { headers: this.getCommonHeaders(), params: new HttpParams() };
return this.http.get(getUserDataUrl, opts)
.pipe(
map(response => {
// here is the problem
console.log(response.json());
return response.json()
}),
catchError(this.handleErrors)
);
In the opts headers I have mentioned the data type:
getCommonHeaders() {
return new HttpHeaders({
'Content-Type': 'application/json',
'x-auth': this.getToken()
})
}
In the console.log(response.json()) I'm getting only email and _id in the array's object. Adding the same console.log(user) on node.js before res.send(user) is showing the entire data with firstName and lastName
Then I added .lean() to the User function. this allowed the rest of the firstName and lastName to appear. How do I get the entire data without converting them to plain objects?
To me it seems like this is the problem. When you use find() method in mongoose, It gives an array. so you convert that array into json and send using res.send(). so when you access it using Angular. it may be crashing and not giving the correct format so try changing the code in node js like this.
Instead of find() try using findOne() in mongoose like this. I assume you only intend to take one user from this query right ?
// Node.js
router.get('/users/all', authenticate, (req, res) => {
User.findOne({some query}).select('firstName lastName email').then((user) => {
res.send(user); // there was a typo I changed it too. look in the question not user it was users.
});
Try to use res.json("JSON Object"); instead of res.send()..
Else try to check the db using tool like robomongo

Resources