express-validator showing undefined for defined values - forms

I'm sending data to server using fetch:
const post = async(data)=>{
console.log(data)
const response = await fetch("/comments", {
method: "POST",
body:JSON.stringify(data)
});
return response.json();
};
data is console logged, it's a standard object with keys and values. And it arrives to server, same keys and values.
On the server I run this express-validation for sanitizing:
router.use(express.json());
router.post("/",
body("email").isEmail().normalizeEmail(),
body("name").trim().escape(),
body("msg").not().isEmpty().trim().escape(),
(req,res,next)=>{
const errors = validationResult(req);
console.log(errors);
if (!errors.isEmpty()) { res.status(422).json({ errors: errors.array() }); return};
try{
saveComment(req.body, (err,doc) => {
err? next(createError(500, "Couldn't save the document. Try again.")):
res.json({msg:"saved"});
});
} catch(e) {
next(createError(500, ISE));
}
});
And what I get is:
Result {
formatter: [Function: formatter],
errors: [
{
value: undefined,
msg: 'Invalid value',
param: 'email',
location: 'body'
},
{
value: undefined,
msg: 'Invalid value',
param: 'msg',
location: 'body'
}
]
}
POST /comments 422 17.821 ms - 126
What is the error?

Set header in the fetch function:
headers: {"Content-Type":"application/json"}

Related

Unable to receive mail sent via sendgrid

I'm creating a contact form using Nextjs and SendGrid, according to this header status
202
{
server: 'nginx',
date: 'Thu, 08 Dec 2022 16:29:25 GMT',
'content-length': '0',
connection: 'close',
'x-message-id': 'CaVdpVAURza6JrUF7yIQQA',
'access-control-allow-origin': 'https://sendgrid.api-docs.io',
'access-control-allow-methods': 'POST',
'access-control-allow-headers': 'Authorization, Content-Type, On-behalf-
of, x-sg-elas-acl',
'access-control-max-age': '600',
'x-no-cors-reason':
'https://sendgrid.com/docs/Classroom/Basics/API/cors.html',
'strict-transport-security': 'max-age=600; includeSubDomains'
}
the email is sent but I find nothing in my inbox,
and this error occurs in the terminal
API resolved without sending a response for /api/contact, this may result in stalled requests.
I don't know what mistake I've done but. I invite you to look at my code bellow:
API :
import sgMail from "#sendgrid/mail";
export default function handler(req, res) {
if (req.method !== "POST") {
res.status(405).json({ message: "INVALID_METHOD" });
return;
}
// Variables from the client side
var name = req.body.name;
var email= req.body.email;
var subject= req.body.subject;
var content = req.body.content;
// auto line break message
const message = content
.replace(/\n/g, "<br>")
.replace(/\r/g, "<br>")
.replace(/\t/g, "<br>")
.replace(/<(?!br\s*\/?)[^>]+>/g, "");
// giving the api key API
sgMail.setApiKey(process.env.KEY_SENDGRID);
// Creating message
const sendGridMail = {
to: "arotiana4612#gmail.com",
from: "kaspersky2mahanaima#gmail.com",
subject: subject,
templateId: "d-b48909edf062437e8442f861a4c8be29",
dynamic_template_data: {
name: name,
email: email,
subject: subject,
content: message,
},
};
// SENDING MESSAGE VIA SENDGRID
(async () => {
try {
await sgMail.send(sendGridMail)
.then((response) => {
console.log(response[0].statusCode)
console.log(response[0].headers)
})
.catch((error) => {
console.error(error)
})
} catch (err){
console.error(err);
res.status(500).json({
error:JSON.stringify(err),
message: "ERROR_WITH_SENDGRID",
});
}
})();
}
And this is the method from the client side that from which I get the data:
const onSubmit: SubmitHandler<Inputs> = async (formData) => {
if (!isLoading) {
setIsLoading(true);
const response = await fetch("/api/contact", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(formData),
});
const result = await response.json();
setIsLoading(false);
if (!response.ok) {
console.log("error sending email:",result);
} else {
console.log("ok");
}
return result;
}
};
I want to receive the mail in my inbox. Your help would be very appreciated, I'm strugling

how to reset form data after successfull axios post request

I have modalform component made using Alpine js and axios for POST request.
But I cannot understand few things:
How to reset form data after succesfull POST request.
I see error in console TypeError: this.resetFields is not a function
How to get errors to show them for the user if POST request is failed due to validation errors with 422 status code.
I want to bind errors.message to AlpineJs variable errors and then show it on the webpage using <p x-text="errors" class="text-red-600"></p>, but this.errors = error.message; seems not working, because in AlpineJS devtools in Chrome errors variable doesn't change.
function modalform() {
return {
mailTooltip: false,
instagramTooltip: false,
openModal: false,
formData: {
name: '',
phone: '',
email: '',
address: '',
message: '',
_token: '{{ csrf_token() }}'
},
message: '',
errors: '',
loading: false,
sent: false,
buttonLabel: 'Send',
resetFields() {
this.formData.name = '',
this.formData.phone = '',
this.formData.email = '',
this.formData.address = '',
this.formData.message = ''
},
submitData() {
this.buttonLabel = 'Sending...';
this.loading = true;
this.message = '';
axios.post('/modalform', this.formData)
.then(function (response) {
console.log(response);
this.resetFields();
this.message = response.data.name;
})
.catch(function (error) {
console.log(error);
this.errors = error.message;
});
},
}
}
```
You have a scoping issue. If you use the old function(response){...} style, then this refers to the object it was called on (axios). However is you replace it with the arrow function, then this will refer to the first non-arrow function object, in this case: the Alpine.js component.
axios.post('/modalform', this.formData)
.then((response) => {
console.log(response);
this.resetFields();
this.message = response.data.name;
})
.catch((error) => {
console.log(error);
this.errors = error.message;
});

Axios post method returning 404 status code

I'm trying to hit rest endpoint which requires multipart file as input parameter from Express. I'm able to hit this endpoint via Postman.
But this endpoint is returning 404 status code in Express. How can I resolve this issue ?
const file = req['file'].buffer.toString('base64');
const form_data = new FormData();
form_data.append('file', file);
axios.post('http://localhost:10000/user/', form_data, {
headers: form_data.getHeaders()
}).then((response) => {
console.log("RESPONSE RECEIVED: ", response);
Id = response.data;
}).catch((err) => {
console.log("AXIOS ERROR: ", err);
Id = null;
});
ERRROR:
=======
data: {
timestamp: '2021-05-21T04:43:10.860+0000',
status: 404,
error: 'Not Found',
message: 'No message available',
path: '/user/'
}
},
isAxiosError: true,
toJSON: [Function: toJSON]
}

Fiware ngsi-javascript node-fetch error when creating entity

I use this module : https://github.com/cenidetiot/ocb-sender
I have one file txt and i read line by line. Each line is a new entity. Sometimes if one of this entity has big information i get this get this error when trying create entity:
This is the code to create entity:
createEntity(entity, headers = {}){
this.addTimeStampEntity(entity);
let t = this
const promise = new Promise(function (resolve, reject) {
headers['Content-Type'] = 'application/json';
const options = { // assign the request options
method: 'POST',
headers: headers,
body: JSON.stringify(entity)
};
fetch(t._URLContext+'/entities', options)
.then(function(res) {
resolve({status : res.status, message:"Entity
})
.catch(function(err){
reject(new Error(`An error has occurred with the creation of the entity: ${err}`))
});
})
return promise; // returns the promise
}
And i get this error:
Error: An error has occurred with the creation of the entity:
FetchError: request to http://192.168.1.5:1026/v2/entities failed, reason: socket hang up
at /Users/helderoliveira/MyApps/MicroServices/connector-fiware/node_modules/ocb-sender/lib/OCB.js:209:28
So i try use timeout but doesn´t work.
import AbortController from 'abort-controller';
const controller = new AbortController();
const timeout = setTimeout(
() => { controller.abort(); },
150,
);
fetch(url, { signal: controller.signal })
.then(res => res.json())
.then(
data => {
useData(data)
},
err => {
if (err.name === 'AbortError') {
// request was aborted
}
},
)
.finally(() => {
clearTimeout(timeout);
});
</pre></code>
can you help me understand this problem ?
Thank you!

Convert Http Response to Json object Ionic 3

The below response is returned upon calling the signup function
Response {_body: "string(85) "{"message":"A customer with the same email
already exists in an associated website."}"↵", status: 200, ok: true,
statusText: "OK", headers: Headers, …}
headers: Headers {_headers: Map(1), _normalizedNames: Map(1)}
ok: true
status: 200
statusText: "OK"
type: 2
url: "http://127.0.0.1/sandbox/M2API/signup/signup"
_body: "string(85) "{"message":"A customer with the same email already exists in an associated website."}"↵"
__proto__: Body
Signup Function:
signup() {
this.authServiceProvider.postData(this.userData, "signup").then((result) => {
this.responseData = result;
console.log(this.responseData);
if( (JSON.stringify(this.responseData._body)) != "" ) {
this.navCtrl.setRoot(HomePage);
} else {
console.log("User already exists");
}
}, (err) => {
//connection failed error message
console.log("something went wrong");
});
}
When i do console.log(JSON.stringify(this.responseData)); backslahes are added to json object
How to avoid that and access message in the response.
Use this
import 'rxjs/add/operator/map';
this.http.get('YOUR_API_ENDPOINT').map(res => res.json()).subscribe(data => {
console.log(data);
});