Search Data not working Angular NodeJS API - node.js

i am created the search part using angular and node js. i have tested through the postman it is working fine. when connect with frond end anqular application is it not working error displayed
Failed to load resource: the server responded with a status of 404 (Not Found)
what i tried so far i attached below please check.
i tried on the url http://localhost:9001/user/findOne?first_name=kobinath
this is working well on postman but tested through the anqular didn't work. i attached the code what i tried so far.
employee.component.ts
search()
{
let name= {
"first_name" : this.first_name
};
this.http.post("http://localhost:9001/user/findOne",name).subscribe((resultData: any)=>
{
console.log(resultData);
});
}
employee.component.html
<form>
<div class="form-group">
<label>First Name</label>
<input type="text" [(ngModel)]="first_name" [ngModelOptions]="{standalone: true}" class="form-control" id="name" placeholder="Enter Name">
</div>
<button type="submit" class="btn btn-primary mt-4" (click)="search()" >Search</button>
</form>
</div>

What I noticed: With Postman you send first_name as a query parameter, but in your Angular-code you attach it to the request-body.
To achieve the equivalent of what you do in Postman, you could use the following code:
search(firstName: string) {
const params = new HttpParams().set('first_name', firstName);
const body = {
first_name : firstName
};
this.http.post("http://localhost:9001/user/findOne", body, { params: params })
.subscribe((resultData: any)=>
{
console.log(resultData);
});
}
Btw: Why don't you use GET instead of POST?

Related

Post image file using axios in react app sending strange data to backend

I'm currently trying to post a photo file upload to my backend, to be stored in the file system. However, whenever I do, it produces an absolutely bizarre string of numbers / letters when I console log the req.body.
I've no idea what this is, why it's happening or how to convert it into the image I need to store in my file system.
Here's my uploadPhoto and buttonClick (aka submit) functions:
const uploadPhoto = (e) => {
e.preventDefault()
setPreviewPhoto(URL.createObjectURL(e.target.files[0]))
setPhotoFile(e.target.files[0])
}
const buttonClick = async (e) => {
e.preventDefault()
const formData = new FormData()
formData.append('photoFile', photoFile)
await axios.post("/api/uploadProfilePicture", formData, { headers: { 'content-type': 'multipart/form-data' }}, { transformRequest: formData => formData })
}
And here's my form that's used to upload the image:
<form className="setup-form" method="POST" encType="multipart/form-data" onSubmit={buttonClick}>
<label className="setup-label">Your name</label>
<input className="setup-input" type="text" name="name" onChange={onChange} value={name} />
<label className="setup-label">Your photo</label>
<div className="setup-photo-hint-container">
<div className="setup-photo-div">
<label for="photoFile" className="setup-photo-label">Upload</label>
<input className="setup-photo-input" id="photoFile" type="file" onChange={uploadPhoto} name="photoFile" />
</div>
</div>
</form>
Does anyone have any idea what I'm doing wrong here? I don't understand why it's going to the request body for one, or why it's producing these characters for another.

How to send email with ReactJS and SendGrid?

I have setup and account on SendGrid. I have got the API key and Node.js methods. I am creating an web app with React js. I want to send emails through SendGrid. I am unable to find any solution. Please help me with my question with an example.
Its not possible with react as it is a frontEnd library, if you try to implement with react you will get these errors
---> Refused to set unsafe header "User-Agent"
If you need to set those headers then you'll need to make the request from your server and not your visitor's browser.
So this is not possible from react and you will need to use some backend or firebase for it.
//Form.js
class Form extends React.Component {
constructor() {
super();
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(event) {
event.preventDefault();
const data = new FormData(event.target);
fetch('/api/form-submit-url', {
method: 'POST',
body: data,
});
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label htmlFor="username">Enter username</label>
<input id="username" name="username" type="text" />
<label htmlFor="email">Enter your email</label>
<input id="email" name="email" type="email" />
<label htmlFor="birthdate">Enter your birth date</label>
<input id="birthdate" name="birthdate" type="text" />
<button>Send data!</button>
</form>
);
}
}
//index.js
const sgMail = require('#sendgrid/mail');
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
const msg = {
to: test#example.com',
from: 'test#example.com',
subject: 'Sending with SendGrid is Fun',
text: 'and easy to do anywhere, even with Node.js',
html: '<strong>and easy to do anywhere, even with Node.js</strong>',
};
sgMail.send(msg);
You can use MailJS, and use sendgrid for transactional services.
It's easy to use.
There are multiple solutions available.
You could use nodeMailer : https://nodemailer.com/about/
Node mailer even has transport dwritten specifically for Sendgrid : https://www.npmjs.com/package/nodemailer-sendgrid-transport
You could use node package by sendgrid itself : https://github.com/sendgrid/sendgrid-nodejs/tree/main/packages/mail

Cannot read property toLowerCase of undefined using Adonis and PostgreSQL

I'm using Adonis with PostgreSQL and I am trying to implement a search where a user would be able to search through posts using the title
I have my code structured like so
<form action="{{ route('search') }}" method="GET" style="outline:none">
<input class="shadow appearance-none border-2 p-2 h-10" style="outline:none" type="text" name="q" placeholder="Search the forum" value="{{ request.input('q', '') }}">
</form>
and my controller like so
'use strict'
const Post = use('App/Models/Post')
const Database = use('Database')
class SearchController {
async index ({ view, request, response, params }) {
let posts = await Post.query()
.forIndex()
.whereRaw('lower(title) LIKE ?', params.searchString.toLowerCase())
.paginate(request.input('page', 1), 10)
return view.render('index', {
posts
})
}
}
module.exports = SearchController
However, I am getting the following error:
Instead of name='q' try name='searchString' in the form
See https://adonisjs.com/docs/4.1/request#_methods to get query string parameters in adonis

Upload image to database using angular

I got stuck while uploading updating user avatar on my website. I'm using angular and need to upload image using form and get base64 encoding of this image to pass as a parameter into my backend.
onUploadFinished(event){
const avatar ={
avatar:event.file
}
console.log(avatar)
//validate avatar
if(!this.validateService.validateAvatarUpdate(avatar.avatar)){
this.flashMessage.show('Please, select a new avatar', {cssClass: 'alert-danger', timeout:3000});
return false;
}
this.updateService.updateAvatar(avatar).subscribe(data=>{
console.log()
if(data/*.success*/){ //commented cause response doesnt have property success but still registering user without displaying the flash message
this.flashMessage.show('You successfuly changed your avatar', {cssClass: 'alert-success', timeout:3000});
this.router.navigate(['/profile'])
this.authService.getProfile().subscribe(profile=>{
this.user = profile.user;
},
err=>{
console.log(err);
return false;
});
}else{
this.flashMessage.show('Something went wrong', {cssClass: 'alert-danger', timeout:3000});
this.router.navigate(['/profile'])
}
});
}
I was trying to use ng2-image-upload here is html
<h6>Upload new photo...</h6>
<!-- <form (submit)="onUserAvatarSubmit()" enctype="multipart/form-data">
<input type="file" name="avatar" class="text-center center-block well well-sm">
<p></p>
<input class="btn btn-primary" value="Upload" type="submit">
</form> -->
<image-upload name="avatar" [class]="'customClass'"
[headers]="{Authorization: this.authToken}"
[buttonCaption]="'Choose an Image'"
[dropBoxMessage]="'or just drop them here'"
(uploadFinished)="onUploadFinished($event)"
[url]="''">
</image-upload>
Maybe anyone had such experience with uploading images, so give me some tips how to deal with it. Thanks here is a screenshot So you see when displaying this image we can see its base64 but I cant take it.

Ajax status 0, success not firing, no info with the errors thrown

I'm working on an app where the user enters info into a form, the form passes the info to my route, the route passes the info to the db, and then when done, it's supposed to update the page accordingly.
The issues I am having is that when you hit submit, the info does land on the database and gets saved but then on the callback/success/complete part of ajax, they dont fire and you have to hit a manual reload for the info to show up. I'm going to assume that this is because of the readystate of 0.
I've tried many solutions other people here on SO have gotten but to no avail.
Here is my code.
HTML:
<div id="createTodoFormW">
<form method="post" id="createTodoForm">
<input type="text" name="todoCompanyName" id="todoCompanyName" placeholder="Enter a Company name or leave empty if its a personal ToDo "><br>
<input type="text" name="todoTitle" id="todoTitle" placeholder="Enter a Title for this note"><br>
<input type="text" name="todoIsFor" id="todoIsFor" placeholder="Who is this ToDo for? ( If left empty, ToDo will be assigned to [ YOU ] )"><br>
<input type="hidden" name="todoPostedBy" id="todoPostedBy" value="LOGGED IN USER HERE">
<input type="hidden" name="todoCompleted" id="todoCompleted" value="no">
<input type="text" name="todoFirstMessage" id="todoFirstMessage" placeholder="Enter your ToDo message"><br>
<select name="todoPriority" id="todoPriority">
<option id="todoPriorityDefaultSelected" >Please select your ToDo priority</option>
<option id="todoPrioritySelected" selected>green</option>
<option id="todoPrioritySelected">yellow</option>
<option id="todoPrioritySelected">red</option>
</select><br>
<input type="submit">
</form>
</div><!-- createTodoFormW ender -->
express/node route:
app.post("/notesapi", (request, response) =>{
//mongoose.connect(databaseLoc);
const newNoteToAdd = new NotesModel({
todoCompany : request.body.todoCompany,
todoIsFor : request.body.todoIsFor,
todoPostedBy : request.body.todoPostedBy,
todoCompleted : request.body.todoCompleted,
todoPriority : request.body.todoPriority,
todoMessages : request.body.todoMessages,
todoTitle : request.body.todoTitle,
todoDate : currDate
});
newNoteToAdd.save((err, data)=>{
if(err){
console.log("There was an error uploading your data " + err);
}else{
//mongoose.connection.close();
console.log("Data upload success.");
}
});
});
front end js:
$("#createTodoForm").submit(function(evt){
evt.preventDefault();
$.ajax({
type : "POST",
cache : false,
dataType : "json",
contentType : "application/json; charset=utf-8",
url : "/notesapi",
data : JSON.stringify({
todoCompany : $("#todoCompanyName").val(),
todoTitle : $("#todoTitle").val(),
todoPostedBy : $("#todoPostedBy").val(),
todoIsFor : $("#todoIsFor").val(),
todoMessages : $("#todoFirstMessage").val(),
todoPriority : $("#todoPriority").val(),
todoCompleted : false
}),
success : function(){
console.log("did ajax fire and comlete?");
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
if (XMLHttpRequest.readyState == 4) {
console.log("HTTP error (can be checked by XMLHttpRequest.status and XMLHttpRequest.statusText");
}
else if (XMLHttpRequest.readyState == 0) {
console.log("Network error (i.e. connection refused, access denied due to CORS, etc.");
console.log(textStatus);
console.log(errorThrown)
console.log(XMLHttpRequest.readyState);
}
else {
console.log("something weird is happening");
}
}
}); //ajax end
});
I need help. Been on this for days and cant figure it out. The main question i guess is, where is this state coming from and why doesnt my success function run?
thanks in advance for any assistance given.

Resources