Express.js multer don't see text fields only file - ajax

When i use AJAX request to send multipart/form-data form to server containing picture and 3 text fields, multer process only image, but no text-fields. How to extract text fields from there?
FormData constructor
handleSubmit = () => {
let formData = new FormData(this.refs.productSubmit);
this.props.submitProduct(formData);
}
Form
<form action="javascript:void(0);" onSubmit={this.handleSubmit} ref="productSubmit">
<label> Название </label>
<input className={'form-control'} type="text" name="name" />
<label> Цена </label>
<input className={'form-control'} type="text" name="price" />
<label> Описание </label>
<input className={'form-control'} type="text" name="description" />
<label> Изображение </label>
<input className={'form-control'} type="file" name="picture" style={{height: '100%'}}/>
<hr/>
<button className={'btn btn-warning btn-lg'} bsSize={'small'} type="submit"> Добавить </button>
</form>
Async action creator with AJAX call inside
export function submitProduct(formData) {
return function(dispatch) {
return (
$.ajax({
url: '/addproduct',
method: 'post',
cache: false,
contentType: false,
processData: false,
data: formData,
success: data => {
//dispatch(addedProduct());
},
error: (xhr, status, err) => {
console.error(this.props.url, status, err.toString());
}
})
);
};
}
Server-side request processer
app.post('/addproduct', isLoggedIn, isAdmin, upload.single('image'), (req, res) => {
console.log(req);
console.log(req.body);
console.log(req.file);
});
But req.body is undefined. File is accessable. Fields ARE present in payload request, i can see them with firefox devtools.How to get thoose text fields?

Since Express 4.0 you need to manually add the body-parser middleware, otherwise forms don't get parsed and req.body will be undefined.
In your main file, you should do something like this:
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
// ...
module.exports = app;

Related

Return submitted POST data with Alpine.js and new FormData()

I'm attempting to POST some form data, using Alpine.js, to the current page which would then be used by PHP $_GET to run some functionality.
It seems to be returning the entire page in the response, rather than the form data (which then errors out due to it being invalid JSON).
How can I only return the submitted form data in the response?
<form
method="post"
action="./"
class="form__press"
x-on:submit.prevent="
let formData = new FormData();
formData.append('username', 'Chris');
fetch('./', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(formData)
})
.then((response) => response.json())
.then((result) => {
console.log('Success:', result);
})
.catch((error) => {
console.error('Error:', error);
});"
>
<div class="field mb:15#xs">
<label for="pressEmail">Email</label>
<input type="email" name="pressEmail" autocomplete="off" required />
</div>
<div class="field mb:15#xs">
<label for="pressPassword">Password</label>
<input type="password" name="pressPassword" autocomplete="new-password" required />
</div>
<button type="submit" name="submit">Submit</button>
</form>
So the right answer to this is that you need your PHP backend function to return JSON with the correct content-type ("application/json").
However you can also achieve this client side since you've got all the data you want returned.
<form
method="post"
action="./"
class="form__press"
x-on:submit.prevent="
let formData = new FormData();
formData.append('username', 'Chris');
fetch('./', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(formData)
})
.then(() => JSON.parse(JSON.stringify(formData)))
.then((result) => {
console.log('Success:', result);
})
.catch((error) => {
console.error('Error:', error);
});"
>

Need e.preventDefault to save JWT into localStorage

For some reason, when trying to login I need to have e.preventDefault (prevent page reloading) in order to save my JWT into local storage with an AJAX call. So when i have this:
handleLogin(e) {
//Without e.preventDefault, the jwt token is not save -> cannot access api
e.preventDefault();
const email = $('#email').val()
const password = $('#password').val()
const request = {"auth": {
"email": email,
"password": password
}}
$.ajax({
url: "http://localhost:5000/api/user_token",
type: "POST",
data: request,
dataType: "json",
success: function (result){
console.log(result.jwt)
localStorage.setItem("jwt", result.jwt)
}
})
}
Here is my simple form
render(){
return(
<div>
<form>
<input
name="email"
id="email"
type="email"
/>
<input
name="password"
id="password"
type="password"
/>
<button
onClick={this.handleLogin}
>Login</button>
<button
onClick={this.handleLogout}
>Logout</button>
</form>
<button onClick={this.getUsers}>Get Users</button>
{
this.state.users
}
</div>
)
}
I want my page to reload/go to a different page after submitting a successful login. On create-react-app and using a Rails API 5
In your case, you can try this:
success: function (result){
console.log(result.jwt)
localStorage.setItem("jwt", result.jwt)
//page reload
window.location.reload(true);
// or route to another page
window.location.href = 'foo'; // any route
}
But I would recommend to use react router so your app will never loose it's state.
If you have any query, you can ask.

How to send input hidden in React JS?

I have this form, and I would like to send these values. I know we have to use setState() to store data but how does it work for input type="hidden"?
First question: How to store input hidden to setState ?
Second question: How to serialize data like form.serialize() ?
Third question: How to send these serialize values? Ajax or Axios, who is the better?
Here is the code:
handleSubmit(e) {
e.preventDefault();
/**
$.ajax({
url: "post.php",
type: "POST",
data: DATA,
success:function(data) {
}
});
**/
}
<form onSubmit={this.handleSubmit}>
<input type="hidden" name="action" value="login" />
<input type="email" name="email_user" placeholder="Email" />
<input type="password" name="password_user" placeholder="Mot de passe" />
<button type="submit">Login</button>
</form>
The answer is complex for all your questions.
First of all, it depends on the task: if you just want to send asynchonous request to server on form submit, you don't need to use Component state. Here is a link to the relevant section of the documentation. And use refs to access inputs data.
class FormComponent extends React.Component {
constructor(props) {
super(props);
this.onSubmit = this.onSubmit.bind(this);
}
onSubmit(e) {
e.preventDefault();
// Send your ajax query via jQuery or Axios (I prefer Axios)
axios.get('your_url', {
params: {
action: this.actionInput.value,
email: this.emailInput.value,
password: this.passwordInput.value,
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
}
render() {
return (
<form onSubmit={this.onSubmit}>
<input type="hidden" name="action" value="login"
ref={(input) => { this.actionInput = input }} />
<input type="email" name="email_user" placeholder="Email"
ref={(input) => { this.emailInput = input }}/>
<input type="password" name="password_user" placeholder="Mot de passe"
ref={(input) => { this.passwordInput = input }}/>
<button type="submit">Login</button>
</form>
);
}
}
All data can be stored on React's state, but if you still need to have inputs on your form you can do something like this:
const handleSubmit = e => {
e.preventDefault();
const inputs = Object.values(e.target)
.filter(c => typeof c.tagName === 'string' && c.tagName.toLowerCase() === 'input')
.reduce((acc, curr) => ({ ...acc, [curr.name]: curr.value }), {});
setFormVals({ ...formVals, ...inputs });
}
See the demo below:
const Demo = () => {
const [formValues] = React.useState({});
const handleSubmit = e => {
e.preventDefault();
const inputs = Object.values(e.target)
.filter(c => typeof c.tagName === 'string' && c.tagName.toLowerCase() === 'input')
.reduce((acc, curr) => ({ ...acc, [curr.name]: curr.value }), {});
console.log(inputs);
}
return (
<form onSubmit={handleSubmit}>
<input name="name" placeholder="Name" value={formValues.name} />
<input name="email" placeholder="Email" value={formValues.email} />
<input name="hiddenInput" value="hiddenValue" type="hidden" />
<button type="submit">Submit</button>
</form>
);
}
ReactDOM.render(<Demo />, document.getElementById('demo'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.0/umd/react-dom.production.min.js"></script>
<div id="demo"></div>
If you know what the inputs that you need you can do something like this:
const Demo = () => {
const formRef = React.useRef(null);
const [formValues, setFormValues] = React.useState({});
const handleChange = e => {
setFormValues({
...formValues,
[e.target.name]: e.target.value,
});
}
const handleSubmit = e => {
e.preventDefault();
setFormValues({ ...formValues, hiddenInput: formRef.current.hiddenInput.value });
}
return (
<form onSubmit={handleSubmit} ref={formRef}>
<input name="name" placeholder="Name" value={formValues.name} onChange={handleChange} />
<input name="email" placeholder="Email" value={formValues.email} onChange={handleChange} />
<input name="hiddenInput" value="hiddenValue" type="hidden" />
<button type="submit">Submit</button>
<pre>{JSON.stringify(formValues, null, 2)}</pre>
</form>
);
}
ReactDOM.render(<Demo />, document.getElementById('demo'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.0/umd/react-dom.production.min.js"></script>
<div id="demo"></div>
Answering your questions:
Since you know how to use component's state you may set the value as : <input type='text' value={this.state.foo} /> or even via props passing <input type='hidden' value={this.props.foo} />
You don't need to serialise anything at all. Use your component's local state or even a state container like Redux or Flux in order to pick the appropriate data. Take a look at this fairly simple example:
var SuperForm = React.createClass({
getInitialState() {
return {
name: 'foo',
email: 'baz#example.com'
};
},
submit(e){
e.preventDefault();
console.log("send via AJAX", this.state)
},
change(e,key){
const newState = {};
newState[key] = e.currentTarget.value;
this.setState(newState)
},
render: function() {
return (
<div>
<label>Name</label>
<input
onChange={(e) => this.change(e,'name')}
type="text"
value={this.state.name} />
<label>Email</label>
<input
onChange={(e) => this.change(e,'email')}
type="text"
value={this.state.email} />
<button onClick={this.submit}>Submit</button>
</div>
);
}});
Demo
AJAX is a set of web development techniques while Axios is a JavaScript framework. You may use jQuery, Axios or even vanilla JavaScript.

Node JS Form Sumit using Ajax

I am new in Node JS , I want to submit a form using ajax like all we are doing in PHP/CakePHP but here i am facing a problem.
HTMl code
<form role="form" action="javascript:;" id="myform">
<div class="form-group">
<label for="name">Name:</label>
<input type="text" class="form-control" id="name" name="name" placeholder="Enter Name">
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" class="form-control" id="email" name="email" placeholder="Enter email">
</div>
<button type="submit" class="btn btn-default" id="enter">Submit</button>
</form>
My AJAX code is
$('.btn').click(function(e){
e.preventDefault();
var data = $('#myform').serialize();
$.ajax({
url: '/ajax',
type: 'POST',
cache: false,
data: JSON.stringify(data),
contentType: 'application/json',
success: function(data) {
console.log(data);
console.log(JSON.stringify(data));
},
error: function(jqXHR, textStatus, err){
alert('text status '+textStatus+', err '+err);
}
})
});
app.js code
app.post('/ajax', bodyParser(), function (req, res){
var obj = {};
console.log('body: ' + JSON.stringify(req.body));
var input = JSON.stringify(req.body);
var data = {
name : input.name,
email : input.email
};
var query = db.query("INSERT INTO users set ?",data, function(err, rows){
console.log(query.sql);
if (err)
console.log("Error inserting : %s ",err );
res.send({'success' : true, 'message' : 'Added Successfully'});
});
});
But when i submit this form then it generate an error in node console like
SyntaxError: Unexpected token "
at parse (D:\man_node\node_modules\body-parser\lib\types\json.js:83:15)
I think that, I am not 100% sure, that you should replace var data = $('#myform').serialize(); with var data = $('#myform').serializeArray();

Frontend ajax POST call can't login to Django

I've spent several days to no avail and was wondering if anyone could help me? I am trying to use Django as a backend only with the ultimate goal of porting to a mobile application. I have a form and ajax call in the front end to a url/view in Django (REST API as well if that is relevant), but for some reason that I don't understand the call won't go through to log me in.
Relevant applications:
Django-Userena
Tastypie
Could anyone advise me in the right direction? Below is the code and thank you!
index.html
<script>
$(document).ready(function(){
`//login test`
`$('#login').submit(function(){`
$.ajax({
url: 'http://127.0.0.1:8000/accounts/signin/',
type: 'POST',
//data: loginString,
data: $('#login').serialize(),
success: function() {
alert('Test');
$('#datadisplay').append("<h2>It worked</h2>");
},
error: function(errorThrown){
alert('Error');
alert(errorThrown);
}
});
});
});
</script>
</head>
<body>
<div id="datadisplay"></div>
<input type="submit" id="getdata" value="Submit">
<div id="loginform">
<form name="login" id="login" action="">
<fieldset>
<label for="id_identification">Username</label>
<input type="text" name="identification" id="id_identification" size="30" value="" />
<br/>
<label for="id_password">Password</label>
<input type="password" name="password" id="id_password" size="30" value="" />
<br/>
<input type="submit" name="submit" class="loginbutton" value="Login" />
</fieldset>
</form>
</div>
api.py
class UserResource(ModelResource):
class Meta:
queryset = User.objects.all()
resource_name = 'user'
include_resource_uri = False
allowed_methods = ['get', 'post']
def override_urls(self):
return [url(r"^(?P<resource_name>%s)/signin%s$" %
(self._meta.resource_name, trailing_slash()),
self.wrap_view('signin'), name="api_signin"),
]
def signin(self, request, **kwargs):
self.method_check(request, allowed=['post'])
data = self.deserialize(request, request.raw_post_data, format=request.META.get('CONTENT_TYPE', 'application/json'))
username = data.get('username', '')
password = data.get('password', '')
user = authenticate(username=username, password=password)
if user:
if user.is_active:
login(request, user)
return self.create_response(request, {
'success': True
})
else:
return self.create_response(request, {
'success': False,
'reason': 'disabled',
}, HttpForbidden )
else:
return self.create_response(request, {
'success': False,
'reason': 'incorrect',
}, HttpUnauthorized )
$.ajax({
url: '/accounts/signin/',
type: 'POST',
data: {
csrfmiddlewaretoken: '{{csrf_token}}',
//other variables
},
success: function() {
alert('Test');
$('#datadisplay').append("<h2>It worked</h2>");
},
error: function(errorThrown){
alert('Error');
alert(errorThrown);
}
});

Resources