I am receiving user object from FB API on a React client (localhost:3000).
Then i'm sending it to my node server (localhost:4000)
When the object is received on the node route and i console log it, it SPLITS any value that has '=' sign to ': ' (colon and space). That's breaking my JSON object.
original object being sent from client: (problem is in imageUrl key equal signs)
userInfo {
about: "abcde"
age: 26
email: "test#test.com"
fbProfileLink: "www.some-profile-link-here.com"
gender: "male"
id: null
imageUrl: "https://url-url.url.url/platform/profilepic/?asid=3422352323&height=50&width=50&ext=3422352323&hash=hash"
language: {mainLang: "", speaksEnglish: true}
name: "abcde"
residence: "abcde"
}
This is how i get it in the node server: (turns to 'asid': ...)
"imageUrl":"https://url-url.url.url/url/profilepic/?asid': '3422352323',
height: '50',
width: '50',
ext: '3422352323',
hash: 'hash'
router function:
router.post("/post-test", (req, res, next) => {
console.log("hi amit POST")
console.dir(req.body)
res.end()
})
request sending from client:
axios.post("http://localhost:4000/post-test", user, {
headers: {"Content-Type": "application/x-www-form-urlencoded"}
})
.then(res => {})
.catch(err => {
console.log(err)
})
its like its breaking the string to query params but i just want it as a string
axios.post("http://localhost:4000/post-test", user, {
headers: {"Content-Type": "application/x-www-form-urlencoded"}
})
Here, you are telling the server that you are sending form-urlencoded data. URL-encoded data follows the key=value&key2=value2 format. The server sees the Content-Type header and tries to parse your JSON as URL-encoded data.
Change the Content-Type to the JSON one:
axios.post("http://localhost:4000/post-test", user, {
headers: {"Content-Type": "application/json"}
})
You are sending an incorrect header which is causing the server to parse the values incorrectly.
Change
{"Content-Type": "application/x-www-form-urlencoded"}
to
{"Content-Type": "application/json"}
I'm Assuming you're using express with body parser.
In order to make it work with json, consider bootstrapping your app in the following way:
Server
const express = require("express")
const bodyParser = require('body-parser')
const app = express();
app.use(bodyParser.json());
Client
axios.post("http://localhost:4000/post-test", user, {
headers: {"Content-Type": "application/json"}
});
Payload
{
"about": "abcde",
"age": 26,
"email": "test#test.com",
"fbProfileLink": "www.some-profile-link-here.com",
"gender": "male",
"id": null,
"imageUrl": "https://url-url.url.url/platform/profilepic/?asid=3422352323&height=50&width=50&ext=3422352323&hash=hash",
"language": {
"mainLang": "",
"speaksEnglish": true
},
"name": "abcde",
"residence": "abcde"
}
Result
hi amit POST
{ about: 'abcde',
age: 26,
email: 'test#test.com',
fbProfileLink: 'www.some-profile-link-here.com',
gender: 'male',
id: null,
imageUrl:
'https://url-url.url.url/platform/profilepic/?asid=3422352323&height=50&width=50&ext=3422352323&hash=hash',
language: { mainLang: '', speaksEnglish: true },
name: 'abcde',
residence: 'abcde' }
Related
I am using mailgun(node js) to send an calendar invite, I am able to send invites but it is not adding to calendar automatically.
How we can automate this calendar invite to gmail, outlook calendar?
How can i achieve Yes, Maybe, No or RSVP or accept or reject options for both gmail and outlook using mailgun(node js) using ical-generator, Ex: var ical = require('ical-generator');?
gmail image
outlook image
Hi Robert,
Thanks for the your time and suggestion.
I have tried using the similar .ics file which gamil gives but it really didn't work to auto sync to calendar or "Yes", "No", "May be" options.
Here is the other example what i have written and trying auto calendar sync and "Yes", "MayBe", "No"options.
Using node module 'ical-generator'.
var ical = require('ical-generator');
var eventObj = {
'start' : '2022-06-02T06:59:52.653Z',
'end' : '2022-06-02T07:59:52.653Z',
'title': "Test mail",
'subject': 'Hey There, Im testing API',
'description': 'Hi User',
"Content-Type": "text/calendar,method=REQUEST",
"method": "REQUEST",
'url': "<domain>",
'id' : '125756xr378',
'organiser' : {'name' : 'Narendra M', 'email':'narendrahd#example.in'},
'location' : 'USA, main',
organizer: { name: 'Narendra M', email: 'narendrahd#example.in' },
attendees: [
{ name: 'Narendra M', email: 'narendrahd#example.in', rsvp: true, partstat: 'ACCEPTED', role: 'REQ-PARTICIPANT' },
],
};
var cal = ical();
Creation of an event using ical.
cal.createEvent({
start: eventObj.start,
end: eventObj.end,
summary: eventObj.title,
method: eventObj.method,
uid: eventObj.id, // Some unique identifier
sequence: 0,
subject: eventObj.subject,
description: eventObj.description,
'Content-Type': "text/calendar,method=REQUEST",
location: eventObj.location,
organizer: {
name: eventObj.organiser.name,
email: eventObj.organiser.email
},
attendees: [
{ name: 'Narendra M', email: 'narendrahd#example.in', rsvp: true, partstat: 'ACCEPTED', role: 'REQ-PARTICIPANT' },
],
});
var path = __dirname + eventObj.id + '.ics';
cal.saveSync(path);
craetion of request and rest call to run mailgun API
var request = require('request');
var fs = require('fs');
var options = {
'method': 'POST',
'url': 'https://api.mailgun.net/v3/<domain>/messages',
'headers': {
'Authorization': 'Basic <token>'
},
formData: {
'from': 'noreply#dummy.in',
'to': ['narendrahd#example.in', 'iamnotveda#example.com'],
'subject': 'Hey There, Im testing API',
'text': 'Hi User',
// 'html': '\'<html><body><p>Hi User,</p></body></html>\'',
'attachment': [{
//'value': fs.createReadStream('/Users/invite.ics'),
'value': fs.createReadStream(path),
'options': {
'filename': 'invite.ics',
'contentType': "application/ics,method=REQUEST"
}
},
]
}
};
request(options, function (error, response) {
if (error) throw new Error(error);
console.log(response.body);
});
Thanks in advance.
Narendra
I suspect partstat: 'ACCEPTED' for attendee could be a culprit here, consider changing it to 'NEEDS-ACTION'.
I recommend checking out this answer which doesn't use ical-generator. Export the raw iCal file and compare the output.
I'm trying to send FormData to my backend but when I console.log the req.body it's empty object and I don't know why.
Here is my frontend request:
const createProduct = (e: any) => {
e.preventDefault();
const data = new FormData()
data.append("name", name)
data.append("description", description)
data.append("price", price)
for (const colorAndImage of colorsAndImages) {
data.append('images', colorAndImage.images[0]);
data.append('colors', colorAndImage.colors);
}
data.append("type", type)
fetch('http://localhost:4000/products/create', {
method: 'POST',
body: data
})
Here is how the image file looks like in the console:
File {name: 'iphone_13_pro_max_gold_pdp_image_position-1a__wwen_5.jpg', lastModified: 1642862621798, lastModifiedDate: Sat Jan 22 2022 16:43:41 GMT+0200 (Eastern European Standard Time), webkitRelativePath: '', size: 22194, …}
Here is what I'm sending in the request in Network tab:
name: sdf
description: sdf
price: 234
images: (binary)
colors: red
type: sdf
Here is the controller in backend side:
productController.post('/create', async (req: Request, res: Response) => {
console.log(req)
try {
const data = req.body;
let product = await create(data)
res.status(201).json(product)
} catch (error) {
console.log(error);
//res.status(500).json({error: error})
}
})
And what I see when I try to console.log the request:
{
name: undefined,
description: undefined,
price: undefined,
colors: undefined,
images: undefined,
type: undefined,
likes: undefined
}
Error: Product validation failed: name: Path `name` is required., description: Path `description` is required., price: Path `price` is required., type: Path `type` is required.
My express config:
const corsConfig: cors.CorsOptions = {
credentials: true,
origin: ['http://localhost:3000', 'http://localhost:2000']
}
export default function (app: Application) {
app.use(cors(corsConfig))
app.use(cookieParser());
app.use(express.urlencoded({ extended: false }));
app.use(express.json())
app.use(auth())
}
Not sure why are you using FormData in sending raw data from frontend to backend.
FormData is generally used when you have to send (upload) files. For simple data you can just send JSON object.
Express by default can't parse multipart/form-data, you will have to install a middleware like multer in order to get the data or you can update your data structure in frontend.
let dataToSend = {
name: name,
description: description,
price: price
// Rest of the properties
}
I write here for who can help me, since I'm new to NodeJS, I'm trying to do something simple, but in the end it doesn't work for me.
I want from the frontend, to make a request to the backend, through the ajax post method. When executing it, from the frontend send a JSON object to the backend and then from the backend it must redirect to another page to the frontend (the latter is what I could not achieve)
Example of what I try
Frontend
var objAgente = {
"FIRSTNAME": "PEDRO",
"LASTNAME": "PEREZ",
"NRORUT": "123456789",
"NROAGENT": "3",
"HRCONNECT": "12:12:12"
};
$.ajax({
type: 'POST',
url: '/LoginAgente',
data: JSON.stringify({ "objectData": objAgente}),
success: function(data) {console.log('todo OK')},
contentType: "application/json",
dataType: 'json'
});
Backend
const express = require("express");
const router = express.Router();
router.use(express.json())
router.use(express.urlencoded({ extended: true }))
router.get('/', (req, res)=>{
res.render('loading.html', { title: 'Iniciando Sistema'});
});
router.get('/Inicio', (req,res)=>{
res.render('confInitial.html', { title: 'Inicio de Sistema'});
});
router.get('/Agente', (req,res)=>{
res.render('PanelAgente/Agente.html', { title: 'Equipo solo Agente'});
});
router.post('/LoginAgente', function (req, res) {
var newUser = req.body;
console.log(newUser);
res.redirect('/Agente');
});
module.exports = router;
When I execute the sending of the JSON object to the backend, the data arrives since I can print it by console, but the res.redirect is not fulfilled;
It does not return an error, but it does not redirect me to where I want.
Thank you very much to those who can give me an idea of what happens
Instead of
res.redirect('/Agente');
Try
res.send({redirect: '/Agente'});
UPDATE:
Frontend
var objAgente = {
"FIRSTNAME": "PEDRO",
"LASTNAME": "PEREZ",
"NRORUT": "123456789",
"NROAGENT": "3",
"HRCONNECT": "12:12:12"
};
$.ajax({
type: 'POST',
url: '/LoginAgente',
data: JSON.stringify({ "objectData": objAgente}),
success: function(data) {
if (data && data.redirect) {
window.location.href = data.redirect;
}
},
contentType: "application/json",
dataType: 'json'
});
Hope this helps!
as you are sending request using AJAX , server can not redirect to other page in AJAX request , you have to redirect user after you getting response from AJAX
$.ajax({
type: 'POST',
url: '/LoginAgente',
data: JSON.stringify({ "objectData": objAgente}),
success: function(data, textStatus, request){
// add redirect link here
window.location.href = '/add_link_to_redirect_here';
},
contentType: "application/json",
dataType: 'json'
});
No need to change backend code, since it may be useful in future when will need non-ajax authentication.
So simply try to get Location header from response and redirect using window.location.href
FRONTEND
var objAgente = {
"FIRSTNAME": "PEDRO",
"LASTNAME": "PEREZ",
"NRORUT": "123456789",
"NROAGENT": "3",
"HRCONNECT": "12:12:12"
};
$.ajax({
type: 'POST',
url: '/LoginAgente',
data: JSON.stringify({ "objectData": objAgente}),
success: function(data, textStatus, request){
const redirectTo = request.getResponseHeader('Location');
if (redirectTo) {
window.location.href = redirectTo;
}
},
contentType: "application/json",
dataType: 'json'
});
i think if you're trying to use and see entire body
var newUser = req.body;
console.log(newUser);
you should in your front pass the object like:
data: JSON.stringify(objAgente)
and do what you're doing:
req.body
cause if you're passing you're object into a new object he'll understand that you're gonna access these proprieties inside the obj, like:
req.body.objectData.FIRSTNAME
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 => {
});
I'm trying to post data to an Items API, for instance:
"data": {
"title": "stack",
"notes": "asdsad",
"time": "19:02",
"meridian": "PM",
"type": "Education",
"_id": "5a2f02d3bba3640337bc92c9",
"days": {
"Monday": true,
"Tuesday": false,
"Wednesday": false,
"Thursday": false,
"Friday": false,
"Saturday": false,
"Sunday": false
}
}
However, when using HttpClient to post the data
this.http.post("http://localhost:3000/api/items",
JSON.stringify(item))
.subscribe(
(val) => {
console.log("POST call successful value returned in body",
val);
},
response => {
console.log("POST call in error", response);
},
() => {
console.log("The POST observable is now completed.");
});
I always get the Bad Request 400 response from the Items Controller in the API.
exports.createItem = async function(req, res, next){
// Req.Body contains the form submit values.
console.log(req);
console.log(req.body);
var item = {
id: req.body.id,
title: req.body.title,
days: req.body.days,
notes: req.body.notes,
time: req.body.time,
meridian: req.body.meridian,
type: req.body.type,
completed: req.body.completed,
}
try{
// Calling the Service function with the new object from the Request Body
var createdItem = await ItemService.createItem(item)
return res.status(201).json({status: 201, data: createdItem, message: "Succesfully Created Item"})
} catch(e){
console.log(e);
//Return an Error Response Message with Code and the Error Message.
return res.status(400).json({status: 400, message: "Item Creation was Unsuccesfull"})
}
}
I have already set up BodyParser in my app.js as so
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
In the express console, the output is as follows
_startTime: 2017-12-11T22:35:18.204Z,
_remoteAddress: '::1',
body: {},
secret: undefined,
cookies: {},
signedCookies: {},
route:
Route {
path: '/',
stack: [ [Object], [Object] ],
methods: { post: true } } }
{}
As you can see the body is empty and this is preventing an item from being created. I have gone ahead and tested this using Postman and when sending url encoded form data and raw JSON data the posts are successful and return 200. However, I can never get the application's request to work.
Any help is appreciated as I have been struggling with this for several hours now.
this.http.post("http://localhost:3000/api/items",
JSON.stringify(item) -----> convert JSON object to string
).subscribe(...);
Based on your server side code, I believe that it expects JSON object other than a JSON string, therefore remove JSON.stringify(item)) from your client side, the body of your POST should be JSON object.