get 400 bad request for http post method (upload file) in Angular 7 - angular7

I have something strange and I can not find the raison for that, I have two Angular applications, in the first one I can upload my file correcclty to the back-end and in the second I am using the same code and the same service to upload the file but I get the error 400 bad request and I do not know where to look to find the error?
document.html
<div fxLayout="row" fxFlex fxFill>
<form #ajouterUnFichier=ngForm (ngSubmit)="onSubmitUnFichier(descFichier, fichier)"
fxLayout="column" fxLayoutGap="10px" fxFlexAlign="center center" fxFlex="40%">
<mat-form-field>
<input type="text" matInput #descFichier id="descFichier" placeholder="Entrez le nom">
</mat-form-field>
<input type="file" id="fichier" (change)="choisirFichier($event)" #fichier
accept=".csv, .xlsx, .pdf, .doc"
/>
<div fxLayout="row" fxLayoutGap="10px">
<button type="submit" mat-raised-button color="primary" [disabled]="!ajouterUnFichier.valid">
Enregistrer
</button>
<button type="submit" mat-raised-button color="accent">
Annuler
</button>
</div>
in document.ts
selectedFile: File = null;
choisirFichier(event) {
if (event.target.files.length > 0) {
this.selectedFile = <File>event.target.files[0];
}
}
onSubmitUnFichier(descriptif: any, file: any) {
this.personneDocumentS.createFile(descriptif, this.selectedFile).subscribe(
res => {
if (res.status === 'error') {
console.log('Error');
} else {
console.log('Sucess ************* ');
}
}
);
}
in document.service
createFile(desc: string, fichier: File) {
const fd = new FormData();
fd.append('file', fichier);
fd.append('id_personne', '1');
fd.append('nom_document', 'fileName');
fd.append('descriptif', desc);
return this.httpClient.post<any>('http://localhost/silose/documents/add', fd);
}
In the first app everything going very well but for the second one I have:
zone.js:3243 POST http://localhost/silose/documents/add 400 (Bad Request)
if you have any idea where to look to find the problem
regards

Related

TypeError: Cannot read property 'message' of undefined ---using react-hook-form

I am trying to display an error message when nothing is typed inside the message input form, but when I load the page I get this error 'TypeError: Cannot read property 'message' of undefined'. I am using react-hook-forms. This is my code down below.
import { Button } from "#material-ui/core";
import { Close } from "#material-ui/icons";
import React from "react";
import { useForm } from "react-hook-form";
import "./SendMail.css";
const SendMail = () => {
const { register, handleSubmit, watch, errors } = useForm();
const onSubmit = (formData) =>{
console.log(formData)
}
return (
<div className="sendMail">
<div className="sendMail__header">
<h3>New Message</h3>
<Close className="sendMail__close" />
</div>
<form onSubmit={handleSubmit(onSubmit)}>
<input name='to' placeholder="To" type="text" {...register('to',{required:true})}/>
<input name="subject" placeholder="Subject" type="text" {...register('subject',{required:true})} />
<input
name="message"
placeholder="Message..."
type="text"
className="sendMail__message"
{...register('message',{required:true})}
/>
{errors.message && <p>To is required!!</p>}
<div className="sendMail__send">
<Button
className="sendMail__send"
variant="contained"
color="primary"
type="submit"
>
Send
</Button>
</div>
</form>
</div>
);
};
export default SendMail;
Since v7 the errors object moved to the formState property, so you need to adjust your destructering:
const { register, handleSubmit, watch, formState: { errors } } = useForm();

Angular2 is not hitting Api

Here im trying to hit my Api from ang2 why its not hitting. Even my Fiddler also not caughing traffic please check my code
constructor(private fb: FormBuilder, private _http: Http) {
_http.get('http://localhost:40039/Api/Home/GetEmp').subscribe(result => {
this.ctstArrayList = result.json();
}
)}
doSubmit(): Observable<Customer> {
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this._http.post('http://localhost:40039/Api/Home/SaveEmp', JSON.stringify(this.custobj), options)
.map(this.extractData)
.catch(this.handleError);
}
This is my html code here i implement ngtoch and other some validation
Html code
<form class="form-horizontal" novalidate (ngSubmit)="doSubmit()" [formGroup]="customerForm">
<fieldset>
<div class="form-group" [ngClass]="{'has-error': (customerForm.get('EmpName').touched ||
customerForm.get('EmpName').dirty) &&
!customerForm.get('EmpName').valid }">
<label for="name">Name</label>
<input type="text" class="form-control" formControlName="EmpName" [(ngModel)]="custobj.EmpName" />
<span>Hell{{custobj.EmpName}}</span>
<span class="help-block" *ngIf="(customerForm.get('EmpName').touched ||
customerForm.get('EmpName').dirty) &&
customerForm.get('EmpName').errors">
<span *ngIf="customerForm.get('EmpName').errors.required">
Please enter your first name.
</span>
<span *ngIf="customerForm.get('EmpName').errors.minlength || customerForm.get('EmpName').errors.maxlength">
The first name must be longer than 3 and max6 characters.
</span>
</span>
</div>
<button type="submit" class="btn btn-success btn-block" (click)="doSubmit(custobj)" [disabled]="!(customerForm.valid)">Submit</button>

React Axios to Rails Knock

I am trying to send a POST request from axios to a Rails API using the following function in the React frontend:
export function registerUser({ name, email, password }) {
var postdata = JSON.stringify({
auth: {
name, email, password
}
});
return function(dispatch) {
axios.post(`${API_URL}/user_token`, postdata )
.then(response => {
cookie.save('token', response.data.token, { path: '/' });
dispatch({ type: AUTH_USER });
window.location.href = CLIENT_ROOT_URL + '/dashboard';
})
.catch((error) => {
errorHandler(dispatch, error.response, AUTH_ERROR)
});
}
}
The Knock gem expects the request in the following format:
{"auth": {"email": "foo#bar.com", "password": "secret"}}
My current function seem to generate the correct format (inspecting the request in the browser devtools), but I'm getting the following error:
Uncaught (in promise) Error: Objects are not valid as a React child
(found: object with keys {data, status, statusText, headers, config,
request}). If you meant to render a collection of children, use an
array instead or wrap the object using createFragment(object) from the
React add-ons. Check the render method of Register.
class Register extends Component {
handleFormSubmit(formProps) {
this.props.registerUser(formProps);
}
renderAlert() {
if(this.props.errorMessage) {
return (
<div>
<span><strong>Error!</strong> {this.props.errorMessage}</span>
</div>
);
}
}
render() {
const { handleSubmit } = this.props;
return (
<form onSubmit={handleSubmit(this.handleFormSubmit.bind(this))}>
{this.renderAlert()}
<div className="row">
<div className="col-md-6">
<label>Name</label>
<Field name="name" className="form-control" component={renderField} type="text" />
</div>
</div>
<div className="row">
<div className="col-md-12">
<label>Email</label>
<Field name="email" className="form-control" component={renderField} type="text" />
</div>
</div>
<div className="row">
<div className="col-md-12">
<label>Password</label>
<Field name="password" className="form-control" component={renderField} type="password" />
</div>
</div>
<button type="submit" className="btn btn-primary">Register</button>
</form>
);
}
}
The error is caused by the following line in your code
errorHandler(dispatch, error.response, AUTH_ERROR)
The exception raised clearly explains that. Instead of setting error.response, try to use the actual data from error.response. E.g error.response.data. Also, you can try replacing the error.response with a string and see how that behaves, then reference the string you need from error.response.data.

ionic contact select not working correctly

I have a problem in ionic when I want to open the contacts.
The funny thing is that contacts only open when before clicking to get_contacts() I tab into/activate the textarea. After that the function get_contacts() is working fine - contacts popup as it should.
But only clicking the button (I added two in my container) does not open the contacts - nothing happens. Why????
Here is my code of the container:
<div ng-repeat="message in messages" class="message-wrapper rlt"
on-hold="onMessageHold($event, $index, message)">
....
</div>
<form name="sendMessageForm" ng-submit="sendMessage(sendMessageForm)" style="background-color: black;" novalidate>
<ion-footer-bar class="bar-stable message-footer" style="background-color: black;" keyboard-attach>
<div class="footer-btn-wrap">
<button class="button button-icon icon ion-android-attach" ng-click="choosePhoto()"></button>
</div>
<label class="item-input-wrapper">
<textarea ng-model="input.message" value="" placeholder="Leave a message..."
required minlength="1" maxlength="1500" msd-elastic autofocus></textarea>
</label>
<div class="footer-btn-wrap">
<button class="button button-icon icon ion-android-send footer-btn" type="submit"
ng-disabled="!input.message || input.message === ''">
</button>
<button class="button button-icon icon ion-ios-search-strong" ng-click="get_contacts()">
</button>
</div>
</ion-footer-bar>
</form>
And this is my js......
document.addEventListener('deviceready', function () {
$scope.get_contacts = function (){
navigator.contacts.pickContact(function(contact){
console.log('The following contact has been selected:' + JSON.stringify(contact));
var mobilenr = " no mobile nr ";
var jsonObj = JSON.parse(JSON.stringify(contact));
for (i = 0; i < jsonObj.phoneNumbers.length; i++) {
var phoneNumber = contact.phoneNumbers[i];
if (phoneNumber.type == 'mobile')
{
mobilenr = phoneNumber.value;
}
}
$scope.itemsList.push({"name":contact.name.formatted, "room":mobilenr});
localStorage.setItem("phonecounter",+localStorage.getItem("phonecounter")+1);
},function(err){
console.log('Error: ' + err);
});
}
}, false)
I'm not able to get this thing working, googled and tried almost everything.
Does anybody have a hint?
I tested on iOS - but this should work in any environment, as I understand. Or not?
Thank you in advance - very much

Saving data through AngularJS

Update:
I have replaced <input type=submit to <button ... and also remove the form tag from my html, after modifying my code i do not see it executing my JS and I have a debugger line in the code and it does not break....
I'm trying to POST data and I have all the code in placed and wired-up correctly (I believe) but when I try to Submit my page # My page gets refreshed, I don't see any event is firing and I have set debugger in the JS, and I do not see any JS error in developer tool
What I'm missing here apart from my code?
here is my code:
//HML code
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>My AngularJS App</title>
<script src="../AppScripts/RequesterAdd.js"></script>
</head>
<body>
<form>
<div ng-app="requesterAddModule" ng-controller="requesterAddController" class="container">
<h2> add requester</h2>
<div ng-show="ShowMessage">Record saved Successfully</div>
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>HostModel</h4>
<hr />
<div class="form-group">
<div>First Name:</div>
<div class="col-md-10">
<input type="text" ng-model="FirstName" required class="form-control input-lg" placeholder="First Name" />
</div>
</div>
<div class="form-group">
<div>Middle Name:</div>
<div class="col-md-10">
<input type="text" ng-model="MiddleName" required class="form-control input-lg" placeholder="Middle Name" />
</div>
</div>
<div class="form-group">
<div>Last Name:</div>
<div class="col-md-10">
<input type="text" ng-model="LastName" required class="form-control input-lg" placeholder="Last Name" />
</div>
</div>
<div class="form-group">
<div>eMail Address:</div>
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-envelope"></i></span>
<input type="text" ng-model="Email" required class="form-control input-lg" placeholder="Email Address" />
</div>
</div>
<div class="form-group">
<div>Is Host Active:</div>
<div class="col-md-10">
<input type="checkbox" ng-model="Active" required class="control-label col-md-2" />
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" id="btnCreate" data-ng-click="addRequester_ClickEvent" value="Create" class="btn btn-primary" />
</div>
</div>
</div>
<div>
#Html.ActionLink("Back to List", "Index")
</div>
</div>
</form>
</body>
</html>
//JS:
var requesterAddModule = angular.module("requesterAddModule", []);
requesterAddModule.factory('requesterAddService',
['$http', function ($http) {
return {
addRequester: function (reqesterData) {
console.log(reqesterData);
debugger;
$http({
url: 'PersistRequester',
method: 'POST',
data: reqesterData
}).then (function (response) {
if (response !== 'undefined' && typeof(response) == 'object') {
window.location.href = '/'
}
},
function(response) {
//failed
}
);
}
};
}]);
requesterAddModule.controller('requesterAddController', ['$scope', '$http', '$window', 'requesterAddService', function ($scope, $http, $window, requesterAddService) {
$scope.addRequester_ClickEvent = function () {
var req = {};
debugger;
req["FirstName"] = $scope.FirstName;
req["MiddleName"] = $scope.MiddleName;
req["LastName"] = $scope.LastName;
req["Email"] = $scope.Email;
req["Active"] = $scope.Active;
requesterAddService.addRequester(req);
}
}]);
//MVC Server side code:
[HttpPost]
public JsonResult PersistRequester(Requester requester)
{
var req = requester;
//if (ModelState.IsValid)
// {
req.CreatedDateTime = DateTime.Now;
db.Requesters.Add(requester);
db.SaveChanges();
return Json(new { Status = "Success" });
//}
}
You're using a form without a method and action which will by default post to the current url. I would highly recommend not to use a form or at least not using an <input type="submit" /> which will default in all the browsers to submit the form.
You're clearly using Bootstrap 3 here so why not just remove the form tag and the submit button and replace it with another element which will not trigger the form post and style it with class="btn btn-primary". Some could argue against this practise along the graceful degradation guidelines but since this particular form is not built from ground up to support the non-js scenario, it is best not to allow browser submit at all.
Also, in your service where you're doing the actual post, you specifically tell the page to reload.
if (response !== 'undefined' && typeof(response) == 'object') {
window.location.href = '/'
}
You should pass this data back to the viewmodel so that the view can re-render and display the response.
If you change the url, the view state is lost and the page will simply render again to the initial state.
instead line
<input type="submit" id="btnCreate" data-ng-click="addRequester_ClickEvent" value="Create" class="btn btn-primary" />
please do
<button id="btnCreate" data-ng-click="addRequester_ClickEvent()" class="btn btn-primary" >Create</button>
I've just tested and is working for me replace:
<input type="submit" id="btnCreate" data-ng-click="addRequester_ClickEvent" value="Create" class="btn btn-primary" />
with
<button id="btnCreate" data-ng-click="addRequester_ClickEvent()" value="Create" class="btn btn-primary" >submit</button>
and I've change a bit your service to :
requesterAddModule.factory('requesterAddService',
['$http', function ($http)
{
return {
addRequester: function (reqesterData)
{
console.log(reqesterData);
debugger;
$http.post('PersistRequester', reqesterData).then(function (response)
{
if (response !== 'undefined' && typeof (response) == 'object') {
window.location.href = '/'
}
},
function (response)
{
//failed
}
);
}
};
}]);
it's posting to /home/PersistRequester if method 'PersistRequester' exist in other controller ie : foo controller change
$http.post('PersistRequester', reqesterData).then(function (response)
to $http.post('foo/PersistRequester', reqesterData).then(function (response)

Resources