如何使用reactjs在FORM Submit中做POST并将对象值传递给REST服务?
How to do POST in FORM Submit using reactjs and pass the object value into REST service?
我使用 reactjs 创建了一个登录页面,当我通过 post 方法 rest api 调用发送我的用户 input/password 来进行身份验证时,我收到一个错误。有人可以帮我看看这里出了什么问题吗!!
我想这是因为我无法以 json 格式发送用户名和密码字符串。
这是错误,
<br />
<b>Notice</b>: Undefined variable: error in <b>/var/www/html/app/Controllers/Hafka/HAFKAController.php</b> on line <b>27</b><br />
<br />
<b>Notice</b>: Undefined variable: id in <b>/var/www/html/app/Controllers/Hafka/HAFKAController.php</b> on line <b>29</b><br />
<br />
<b>Notice</b>: Undefined variable: error in <b>/var/www/html/app/Controllers/Hafka/HAFKAController.php</b> on line <b>29</b><br />
{"code":"INVALID_JSON_INPUT","message":"Error decoding JSON input"}
这是我的 app.js 文件,
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
export default class App extends Component {
render() {
return (
<div className="App">
<div className="App-header"></div>
<form
id="main-login"
action="http://don.healthedata.com/admin/login"
method="post">
<h2>
Admin UI Login
</h2>
<label>
<span class="text">user:</span>
<input type="email" name="email"/><br/>
</label>
<br/>
<label>
<span class="text">password:</span>
<input type="password" name="password"/><br/>
</label><br/>
<div class="align-right">
<button type="submit">Submit</button>
</div>
</form>
</div>
);
}
}
解法:
修改和工作 App.js 文件:
import React, {Component} from 'react';
import logo from './logo.svg';
import './App.css';
export default class App extends Component {
constructor(props, context) {
super(props, context);
this.state = { description: '' };
}
onChange(e) {
this.setState({
[e.target.name]: e.target.value
});
}
onSubmit(e) {
e.preventDefault();
fetch(this.props.formAction, {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({description: this.state.description})
});
this.setState({description: ''});
}
render() {
return (
<div className="App">
<form
id="main-login"
action={this.props.action}
method={this.props.method}
onSubmit={this.onSubmit}>
<h2>Admin UI Login</h2>
<label>
<span class="text">user:</span>
<input type="email" name="email"/><br/>
</label>
<br/>
<label>
<span class="text">password:</span>
<input type="password" name="password"/><br/>
</label>
<br/>
<div class="align-right">
<button>Submit</button>
</div>
</form>
</div>
);
}
}
// App.propTypes = { action: React.PropTypes.string.isRequired, method: React.PropTypes.string}
App.defaultProps = {
action: 'http://don.healthedata.com/admin/login',
method: 'post'
};
module.exports = App;
当我提供用户 input/password 并点击提交时,没有任何反应。
你是对的,你收到了这个错误:
{"code":"INVALID_JSON_INPUT","message":"Error decoding JSON input"}
这意味着您没有以 JSON 格式发送数据。您需要处理从表单中获得的信息,创建一个 JSON 对象,然后通过 POST 请求发送它。
您可以使用表单的 onSubmit
属性 来做到这一点。将表单中的数据处理到新函数,然后我建议 using fetch 发送 POST
首先获取你要插入的 url data.Here 首先创建 todoadd.js 文件:
import fetch from 'isomorphic-fetch';
export function createBlogPost(data) {
return fetch('Your Rest url', {
method: 'POST',
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json'
}
}).then(response => {
if (response.status >= 200 && response.status < 300) {
return response;
console.log(response);
window.location.reload();
} else {
console.log('Somthing happened wrong');
}
}).catch(err => err);
}
之后控制您的 UI 在 tododialouge.js 中提交:
import React, { Component, PropTypes } from 'react'
import { connect } from 'react-redux'
import { createBlogPost } from '../../actions/todoadd';
import { addTodo } from '../../actions/todo'
import { setTodoDialogOpen, setErrorText } from '../../actions/todoDialog';
import Dialog from 'material-ui/Dialog';
import FlatButton from 'material-ui/FlatButton';
import RaisedButton from 'material-ui/RaisedButton';
import TextField from 'material-ui/TextField';
const initialstate = {
title: '',
desc: '',
type: '',
imageurl: ''
}
class TodoDialog extends Component {
constructor(props) {
super(props)
this.state = initialstate;
this.onChange = this.onChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
};
onChange(e) {
if (e.target.id === 'title') {
this.setState({ title: e.target.value });
} else if (e.target.id === 'desc') {
this.setState({ desc: e.target.value });
} else if (e.target.id === 'type') {
this.setState({ type: e.target.value });
} else if (e.target.id === 'image') {
this.setState({ imageurl: e.target.value});
console.log(e.target.value);
}
}
handleSubmit() {
const text = {
news_title: this.state.title,
news_description: this.state.desc,
news_type: this.state.type,
news_src_url: this.state.imageurl,
operation:"insert"
}
alert(text.news_src_url);
createBlogPost(text);
setErrorText(undefined);
setTodoDialogOpen(false);
};
render() {
const { messages, todoDialog, setTodoDialogOpen, addTodo, setErrorText } = this.props;
const styles = {
button: {
margin: 12,
},
exampleImageInput: {
cursor: 'pointer',
position: 'absolute',
top: 0,
bottom: 0,
right: 0,
left: 0,
width: '100%',
opacity: 0,
},
};
function handleClose() {
setErrorText(undefined);
setTodoDialogOpen(false);
};
const actions = [< FlatButton label={
messages.cancel || 'cancel'
}
primary={
true
}
onTouchTap={
handleClose
} />, < FlatButton label={
messages.submit || 'submit'
}
primary={
true
}
onTouchTap={this.handleSubmit} />
];
return (
<div>
<Dialog title={messages.todo_add || 'todo_add'} actions={actions} modal={false} open={todoDialog.open} onRequestClose={handleClose}>
<form>
<TextField ref="todoText1" onChange={this.onChange} id='title' hintText={messages.todo_hint1 || 'todo_hint'} errorText={todoDialog.errorText} floatingLabelText={messages.todo_label1 || 'todo_label1'} fullWidth={true} />
<TextField ref="todoText2" onChange={this.onChange} id='desc' hintText={messages.todo_hint2 || 'todo_hint'} errorText={todoDialog.errorText} floatingLabelText={messages.todo_label2 || 'todo_label2'} fullWidth={true} multiLine={true} rows={1} rowsMax={3} />
<TextField ref="todoText3" onChange={this.onChange} id='type' hintText={messages.todo_hint3 || 'todo_hint'} errorText={todoDialog.errorText} floatingLabelText={messages.todo_label3 || 'todo_label3'} fullWidth={true} />
<RaisedButton label='ADD Photo' style={styles.button} labelPosition="before" containerElement="label"><input type='file' onChange={this.onChange} id='image' style={styles.exampleImageInput} /></RaisedButton>
</form>
</Dialog>
</div>
)
}
}
您根据要求处理的其他一些文件。
希望本文对您有所帮助。
我使用 reactjs 创建了一个登录页面,当我通过 post 方法 rest api 调用发送我的用户 input/password 来进行身份验证时,我收到一个错误。有人可以帮我看看这里出了什么问题吗!!
我想这是因为我无法以 json 格式发送用户名和密码字符串。
这是错误,
<br />
<b>Notice</b>: Undefined variable: error in <b>/var/www/html/app/Controllers/Hafka/HAFKAController.php</b> on line <b>27</b><br />
<br />
<b>Notice</b>: Undefined variable: id in <b>/var/www/html/app/Controllers/Hafka/HAFKAController.php</b> on line <b>29</b><br />
<br />
<b>Notice</b>: Undefined variable: error in <b>/var/www/html/app/Controllers/Hafka/HAFKAController.php</b> on line <b>29</b><br />
{"code":"INVALID_JSON_INPUT","message":"Error decoding JSON input"}
这是我的 app.js 文件,
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
export default class App extends Component {
render() {
return (
<div className="App">
<div className="App-header"></div>
<form
id="main-login"
action="http://don.healthedata.com/admin/login"
method="post">
<h2>
Admin UI Login
</h2>
<label>
<span class="text">user:</span>
<input type="email" name="email"/><br/>
</label>
<br/>
<label>
<span class="text">password:</span>
<input type="password" name="password"/><br/>
</label><br/>
<div class="align-right">
<button type="submit">Submit</button>
</div>
</form>
</div>
);
}
}
解法:
修改和工作 App.js 文件:
import React, {Component} from 'react';
import logo from './logo.svg';
import './App.css';
export default class App extends Component {
constructor(props, context) {
super(props, context);
this.state = { description: '' };
}
onChange(e) {
this.setState({
[e.target.name]: e.target.value
});
}
onSubmit(e) {
e.preventDefault();
fetch(this.props.formAction, {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({description: this.state.description})
});
this.setState({description: ''});
}
render() {
return (
<div className="App">
<form
id="main-login"
action={this.props.action}
method={this.props.method}
onSubmit={this.onSubmit}>
<h2>Admin UI Login</h2>
<label>
<span class="text">user:</span>
<input type="email" name="email"/><br/>
</label>
<br/>
<label>
<span class="text">password:</span>
<input type="password" name="password"/><br/>
</label>
<br/>
<div class="align-right">
<button>Submit</button>
</div>
</form>
</div>
);
}
}
// App.propTypes = { action: React.PropTypes.string.isRequired, method: React.PropTypes.string}
App.defaultProps = {
action: 'http://don.healthedata.com/admin/login',
method: 'post'
};
module.exports = App;
当我提供用户 input/password 并点击提交时,没有任何反应。
你是对的,你收到了这个错误:
{"code":"INVALID_JSON_INPUT","message":"Error decoding JSON input"}
这意味着您没有以 JSON 格式发送数据。您需要处理从表单中获得的信息,创建一个 JSON 对象,然后通过 POST 请求发送它。
您可以使用表单的 onSubmit
属性 来做到这一点。将表单中的数据处理到新函数,然后我建议 using fetch 发送 POST
首先获取你要插入的 url data.Here 首先创建 todoadd.js 文件:
import fetch from 'isomorphic-fetch';
export function createBlogPost(data) {
return fetch('Your Rest url', {
method: 'POST',
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json'
}
}).then(response => {
if (response.status >= 200 && response.status < 300) {
return response;
console.log(response);
window.location.reload();
} else {
console.log('Somthing happened wrong');
}
}).catch(err => err);
}
之后控制您的 UI 在 tododialouge.js 中提交:
import React, { Component, PropTypes } from 'react'
import { connect } from 'react-redux'
import { createBlogPost } from '../../actions/todoadd';
import { addTodo } from '../../actions/todo'
import { setTodoDialogOpen, setErrorText } from '../../actions/todoDialog';
import Dialog from 'material-ui/Dialog';
import FlatButton from 'material-ui/FlatButton';
import RaisedButton from 'material-ui/RaisedButton';
import TextField from 'material-ui/TextField';
const initialstate = {
title: '',
desc: '',
type: '',
imageurl: ''
}
class TodoDialog extends Component {
constructor(props) {
super(props)
this.state = initialstate;
this.onChange = this.onChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
};
onChange(e) {
if (e.target.id === 'title') {
this.setState({ title: e.target.value });
} else if (e.target.id === 'desc') {
this.setState({ desc: e.target.value });
} else if (e.target.id === 'type') {
this.setState({ type: e.target.value });
} else if (e.target.id === 'image') {
this.setState({ imageurl: e.target.value});
console.log(e.target.value);
}
}
handleSubmit() {
const text = {
news_title: this.state.title,
news_description: this.state.desc,
news_type: this.state.type,
news_src_url: this.state.imageurl,
operation:"insert"
}
alert(text.news_src_url);
createBlogPost(text);
setErrorText(undefined);
setTodoDialogOpen(false);
};
render() {
const { messages, todoDialog, setTodoDialogOpen, addTodo, setErrorText } = this.props;
const styles = {
button: {
margin: 12,
},
exampleImageInput: {
cursor: 'pointer',
position: 'absolute',
top: 0,
bottom: 0,
right: 0,
left: 0,
width: '100%',
opacity: 0,
},
};
function handleClose() {
setErrorText(undefined);
setTodoDialogOpen(false);
};
const actions = [< FlatButton label={
messages.cancel || 'cancel'
}
primary={
true
}
onTouchTap={
handleClose
} />, < FlatButton label={
messages.submit || 'submit'
}
primary={
true
}
onTouchTap={this.handleSubmit} />
];
return (
<div>
<Dialog title={messages.todo_add || 'todo_add'} actions={actions} modal={false} open={todoDialog.open} onRequestClose={handleClose}>
<form>
<TextField ref="todoText1" onChange={this.onChange} id='title' hintText={messages.todo_hint1 || 'todo_hint'} errorText={todoDialog.errorText} floatingLabelText={messages.todo_label1 || 'todo_label1'} fullWidth={true} />
<TextField ref="todoText2" onChange={this.onChange} id='desc' hintText={messages.todo_hint2 || 'todo_hint'} errorText={todoDialog.errorText} floatingLabelText={messages.todo_label2 || 'todo_label2'} fullWidth={true} multiLine={true} rows={1} rowsMax={3} />
<TextField ref="todoText3" onChange={this.onChange} id='type' hintText={messages.todo_hint3 || 'todo_hint'} errorText={todoDialog.errorText} floatingLabelText={messages.todo_label3 || 'todo_label3'} fullWidth={true} />
<RaisedButton label='ADD Photo' style={styles.button} labelPosition="before" containerElement="label"><input type='file' onChange={this.onChange} id='image' style={styles.exampleImageInput} /></RaisedButton>
</form>
</Dialog>
</div>
)
}
}
您根据要求处理的其他一些文件。 希望本文对您有所帮助。