problem with mail function from netlify to mailgun - json

I have a Hugo site running on Netlify with Mailgun-js for a couple of forms.
I try and run a simple contact function in Netlify but get a JSON related error
Jun 24, 12:57:15 PM: 7af5f746 ERROR Invoke Error {"errorType":"SyntaxError","errorMessage":"Unexpected end of JSON input","stack":["SyntaxError: Unexpected end of JSON input"," at JSON.parse ()"," at Runtime.exports.handler (/var/task/functions/contact/contact.js:11:19)"," at Runtime.handleOnceNonStreaming (/var/runtime/Runtime.js:73:25)"]}
if I remove the JSON.parse I get the following:
{"errorType":"SyntaxError","errorMessage":"Unexpected token b in JSON at position 0","trace":["JSON.parse ()","t.handler
I am at a total loss to understand how and where to debug this :(
This is the code which used to work:
require('dotenv').config()
const { MAILGUN_API_KEY, MAILGUN_DOMAIN, MAILGUN_URL, FROM_EMAIL_ADDRESS, CONTACT_TO_EMAIL_ADDRESS } = process.env
const mailgun = require('mailgun-js')({ apiKey: MAILGUN_API_KEY, domain: MAILGUN_DOMAIN, host: "api.eu.mailgun.net" })
exports.handler = async (event, context, callback) => {
/* the server-side functionality */
const data = JSON.parse(event.body)
var text = `Dear ${data.name}, \n\n`
text += `${data.message} \n`
text += `Country of residence: ${data.country} \n`
const style = "<style> </style>"
var body = `<html>${style}<div>`
body += `<p>Dear ${data.name},</p>`
body += `<h4>Your message:</h4><p>${data.message}</p>`
body += `<p>Country of residence: ${data.country}</p>`
body += `</div></html>`
let response
try {
response = await mailgun.messages().send({
to: data.email,
bcc: CONTACT_TO_EMAIL_ADDRESS,
from: FROM_EMAIL_ADDRESS,
subject: `Enquiry for Summertime from ${data.arrdate}`,
text: text,
html: body
})
}
catch (error) {
console.log('Error: ', error)
return {
statusCode: error.statusCode || 500,
headers: { "Access-Control-Allow-Origin": "*" },
body: JSON.stringify({ error: error.message })
}
}
return {
statusCode: 200,
headers: { "Access-Control-Allow-Origin": "*" },
body: JSON.stringify({ result: 200 })
}
}```

Related

how to fetch large json from a post in angular6/7

I have migrated a piece of code to be able to export data as excel file in angular.
I assume the fact that the json is well formed and send from the server to the angular side. I can see it in the network frame in th browser.
For small json, it's ok but when the size of the json starts to be large, the answer still failed.
This following code corresponding to the service call
exportSynthesis(recordId: number, moduleId: number) {
const body = null;
return this.http.post(this.apiUrl + `/data`
+ `${recordId}/module/${moduleId}`, body,
{
headers: new HttpHeaders({ 'Content-Type': 'application/json' }),
observe: 'response', responseType: 'json' }).pipe(
map((resp: any) => {
return resp.body;
}));
}
and here, its the method which manages the return.
exportSynthesis() {
this.service.exportSynthesis(this.recordId, this.moduleId)
.subscribe(
(exportResult) => { this.exportResult = exportResult; },
err => {
console.log('err:', err);
this.errorHandlerService.handleError('failed', err);
},
() => {
console.log('json:', this.exportResult);
const worksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(this.exportResult);
const workbook: XLSX.WorkBook = { Sheets: { 'data': worksheet }, SheetNames: ['data'] };
const excelBuffer: any = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
const blob = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8' });
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = '(GEO) ' + this.record.label + ' - name.xlsx';
a.click();
window.URL.revokeObjectURL(url);
a.remove();
});
}
Currently, i do not manage to understand why it still finish in error and I get only "ok" in the console log.
Any idea?
regards
Angular's HttpClientModule default response is a json.
Your problem is that you try to access the body property of the HTTP response, but Angular interprets that as you trying to access the body property in the body of the response.
Remove observe and responseType from your post request and treat the response as a json. It should work.
find:
just need to use text as json
return this.http.post(this.apiUrl + `/geo/v1/synthesis/xls/record/`
+ `${recordId}/module/${moduleId}`, body,
{
headers: headers,
observe: 'response',
responseType: 'text' as 'json'}).
map((resp: any) => {
return resp.body;
});
}

Deno post method empty request body

I am currently developing a proof-of-concept REST api app with Deno and I have a problem with my post method (getAll et get working). The body of my request does not contain data sent with Insomnia.
My method :
addQuote: async ({ request, response }: { request: any; response: any }) => {
const body = await request.body();
if (!request.hasBody) {
response.status = 400;
response.body = { message: "No data provided" };
return;
}
let newQuote: Quote = {
id: v4.generate(),
philosophy: body.value.philosophy,
author: body.value.author,
quote: body.value.quote,
};
quotes.push(newQuote);
response.body = newQuote;
},
Request :
Response :
I put Content-Type - application/json in the header.
If I return only body.value, it's empty.
Thanks for help !
Since value type is promise we have to resolve before accessing value.
Try this:
addQuote: async ({ request, response }: { request: any; response: any }) => {
const body = await request.body(); //Returns { type: "json", value: Promise { <pending> } }
if (!request.hasBody) {
response.status = 400;
response.body = { message: "No data provided" };
return;
}
const values = await body.value;
let newQuote: Quote = {
id: v4.generate(),
philosophy: values.philosophy,
author: values.author,
quote: values.quote,
};
quotes.push(newQuote);
response.body = newQuote;
}

node.js - Send POST data with raw json format with require module

we have storage array which supports REST API. I am able to do all ( GET/POST/DELETE/PUT) through postman and need to implement one of POST operation through Node.js script.
I am successful in node.js GET operation. But still not able to get the simple POST operation through multiple tries with various forms. here is the codes of both GET and PUT. Also the successful POST operation screenshot by the postman.
Appreciate any help.
GET: Node.js code ( working ):
var request = require('request');
function get_trustyou(trust_you_id, callback){
var options = {
url: 'https://xxxxxx/api/json/v2/types/consistency-groups',
rejectUnauthorized: false,
method: 'GET',
type: 'application/json',
auth:{
user: 'xxxxx',
pass: 'xxx'
}
};
var res = '';
request(options, function ( error, resp, body ) {
if ( !error && resp.statusCode == 200){
res = body;
}
if (error) {
console.log("this is error" + error);
}
callback(res);
});
}
get_trustyou("674fa44c-1fbd-4275-aa72-a20f262372cd", function(resp){
console.log("Here is the result" + resp);
});
POST: Node.js code ( Not working ):
var request = require('request');
function get_trustyou(trust_you_id, callback){
var options = {
body: postData,
url: 'https://xxxx/api/json/v2/types/consistency-groups',
rejectUnauthorized: false,
method: 'POST',
type: 'application/json',
auth:{
user: 'xxxx',
pass: 'xxxxx'
},
form: {
'consistency-group-name': 'TEST-CG'
}
};
request(options, function ( error, resp, body ) {
if ( !error && resp.statusCode == 200){
res = body;
}
if (error) {
console.log("this is error" + error);
}
callback(res);
});
}
get_trustyou("674fa44c-1fbd-4275-aa72-a20f262372cd", function(resp){
console.log("this is the responce" + resp);
});

Trying to get the gender using facebook Messenger Bot call

Hi I am trying to get the gender back from a curl request in node.js.
I am following these instructions https://developers.facebook.com/docs/messenger-platform/user-profile
my code is below, but i get an error during the execution.
I call the below using fbUserInfo(recipentId).catch(console.error);
const fbUserInfo = (id) => {
//const body = JSON.stringify({
// recipient: { id },
// message: { text },
//});
const qs = 'access_token=' + encodeURIComponent(FB_PAGE_TOKEN1);
return fetch('https://graph.facebook.com/v2.6/' + id + '?fields=first_name,last_name,profile_pic,locale,timezone,gender&' + qs, {
method: 'POST',
headers: {'Content-Type': 'application/json'},
//body,
})
.then(rsp => rsp.json())
.then(json => {
if (json.error && json.error.message) {
throw new Error(json.error.message);
}
return json;
});
console.log('=== ' + json); // I was hoping this would output the returned json
}; // const

cors unexpected end of JSON input

I am parsing my json on end but I am still receiving this error.
'use strict';
const http = require('http');
const tools = require('./tools.js');
const server = http.createServer(function(request, response) {
console.log("received " + request.method + " request from " + request.headers.referer)
var body = "";
request.on('error', function(err) {
console.log(err);
}).on('data', function(chunk) {
body += chunk;
}).on('end', function() {
console.log("body " + body);
var data = JSON.parse(body); // trying to parse the json
handleData(data);
});
tools.setHeaders(response);
response.write('message for me');
response.end();
});
server.listen(8569, "192.168.0.14");
console.log('Server running at 192.168.0.14 on port ' + 8569);
Data being sent from the client:
var data = JSON.stringify({
operation: "shutdown",
timeout: 120
});
I successfully receive the json but I am unable to parse it.
Update:
I've updated the code to include the server code in its entirety.
To be perfectly clear, using the following code:
....
}).on('end', function() {
console.log("body " + body);
var json = JSON.parse(body); // trying to parse the json
handleData(json);
});
I get this:
However, this:
....
}).on('end', function() {
console.log("body " + body);
//var json = JSON.parse(body); // trying to parse the json
//handleData(json);
});
produces this
Can we see the server code, please?
Here is a working end-to-end example which is (more or less) what you are attempting, I believe.
"use strict";
const http = require('http');
/********************
Server Code
********************/
let data = {
operation: 'shutdown',
timeout: 120
};
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.write(JSON.stringify(data));
res.end();
});
server.listen(8888);
/********************
Client Code
********************/
let options = {
hostname: 'localhost',
port: 8888,
path: '/',
method: 'POST',
headers: {
'Accept': 'application/json'
}
};
let req = http.request(options, res => {
let buffer = '';
res.on('data', chunk => {
buffer += chunk;
});
res.on('end', () => {
let obj = JSON.parse(buffer);
console.log(obj);
// do whatever else with obj
});
});
req.on('error', err => {
console.error('Error with request:', err);
});
req.end(); // send the request.
It turns out that as this is a cross-origin(cors) request, it was trying to parse the data sent in the preflighted request.
I simply had to add an if to catch this
....
}).on('end', function() {
if (request.method !== 'OPTIONS') {
var data = JSON.parse(body);
handleData(data);
}
});
Further reading if you're interested: HTTP access control (CORS)
Put the identifiers in quotes.
{
"operation": "shutdown",
"timeout": 120
}
http://jsonlint.com/ Is a helpful resource.