对node.js api响应js:axios post请求
您好,我在使用axios发送请求中的所有数据时遇到一些问题。我创建了node.js api,现在我想使用axios和react js作为前端技术从表单发送用户注册数据 我在react after submit和now中更新了我的状态,当时我想通过“内容类型”发送信息:“application/x-www-form-urlencoded”我的名字是not send(null),最后一个值是-location get“\” 我在《邮递员》中测试了这个请求,效果很好 有什么建议吗 my node.js路由:对node.js api响应js:axios post请求,node.js,reactjs,axios,Node.js,Reactjs,Axios,您好,我在使用axios发送请求中的所有数据时遇到一些问题。我创建了node.js api,现在我想使用axios和react js作为前端技术从表单发送用户注册数据 我在react after submit和now中更新了我的状态,当时我想通过“内容类型”发送信息:“application/x-www-form-urlencoded”我的名字是not send(null),最后一个值是-location get“\” 我在《邮递员》中测试了这个请求,效果很好 有什么建议吗 my node.js
app.post('/users', (req, res) => {
const user = { firstName: req.body.firstName, lastName: req.body.lastName, age: req.body.age, photo: req.body.photo, email: req.body.email, description: req.body.description, hobbies: req.body.hobbies, location: req.body.location };
db.collection('users').insert(user, (err, result) => {
if (err) {
res.send({ 'error': 'An error has occurred' });
} else {
res.send(result.ops[0]);
}
});
});
import React, { Component } from 'react';
import axios from 'axios';
class Register extends Component {
state = {
firstName: '',
lastName: '',
age: '',
email: '',
description: '',
hobbies: '',
location: '',
};
handleFirstNameChange = event => {
this.setState({
firstName: event.target.value,
});
}
handleLastNameChange = event => {
this.setState({
lastName: event.target.value,
});
}
handleEmailChange = event => {
this.setState({
email: event.target.value,
});
}
handleAgeChange = event => {
this.setState({
age: event.target.value,
});
}
handleDescriptionChange = event => {
this.setState({
description: event.target.value,
});
}
handleHobbiesChange = event => {
this.setState({
hobbies: event.target.value,
});
}
handleLocationChange = event => {
this.setState({
location: event.target.value,
});
}
handleSubmit = event => {
event.preventDefault();
const user = {
firstName: this.state.firstName,
lastName: this.state.lastName,
age: this.state.age,
email: this.state.email,
description: this.state.description,
hobbies: this.state.hobbies,
location: this.state.location,
};
//x-www-form
let formBody = [];
for (let property in user) {
let encodedKey = encodeURIComponent(property);
let encodedValue = encodeURIComponent(user[property]);
formBody.push(encodedKey + "=" + encodedValue);
}
formBody = formBody.join("&");
console.log(formBody);
axios.post(`http://localhost:8000/users`, { formBody }, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } })
.then(res => {
console.log(res);
console.log(res.data);
})
}
render() {
return (
<div className="register">
<h2>Register</h2>
<form onSubmit={this.handleSubmit}>
<label htmlFor="firstName">First Name:</label>
<input type="text" id="firstName" name="firstName" onChange={this.handleFirstNameChange} />
<br/>
<label htmlFor="lastName">Last Name:</label>
<input type="text" id="lastName" name="lastName" onChange={this.handleLastNameChange} />
<br/>
<label htmlFor="email">Email:</label>
<input type="text" id="email" name="email" onChange={this.handleEmailChange} />
<br/>
<label htmlFor="age">Age:</label>
<input type="text" id="age" name="age" onChange={this.handleAgeChange} />
<br/>
<label htmlFor="description">Description of myself:</label>
<input type="text" id="description" name="description" onChange={this.handleDescriptionChange} />
<br/>
<label htmlFor="hobbies">Hobbies:</label>
<input type="text" id="hobbies" name="hobbies" onChange={this.handleHobbiesChange} />
<br/>
<label htmlFor="location">Location:</label>
<input type="text" id="location" name="location" onChange={this.handleLocationChange} />
<br/>
<input type="submit" value="Register" />
</form>
</div>
);
}
}
export default Register;
{
"_id": {
"$oid": "5b3af97a10d5b622289ddbbc"
},
"firstName": null,
"lastName": "test",
"age": "222",
"photo": null,
"email": "test@gmail.com",
"description": "test",
"hobbies": "test",
"location": "test\"}"
}
react注册:
app.post('/users', (req, res) => {
const user = { firstName: req.body.firstName, lastName: req.body.lastName, age: req.body.age, photo: req.body.photo, email: req.body.email, description: req.body.description, hobbies: req.body.hobbies, location: req.body.location };
db.collection('users').insert(user, (err, result) => {
if (err) {
res.send({ 'error': 'An error has occurred' });
} else {
res.send(result.ops[0]);
}
});
});
import React, { Component } from 'react';
import axios from 'axios';
class Register extends Component {
state = {
firstName: '',
lastName: '',
age: '',
email: '',
description: '',
hobbies: '',
location: '',
};
handleFirstNameChange = event => {
this.setState({
firstName: event.target.value,
});
}
handleLastNameChange = event => {
this.setState({
lastName: event.target.value,
});
}
handleEmailChange = event => {
this.setState({
email: event.target.value,
});
}
handleAgeChange = event => {
this.setState({
age: event.target.value,
});
}
handleDescriptionChange = event => {
this.setState({
description: event.target.value,
});
}
handleHobbiesChange = event => {
this.setState({
hobbies: event.target.value,
});
}
handleLocationChange = event => {
this.setState({
location: event.target.value,
});
}
handleSubmit = event => {
event.preventDefault();
const user = {
firstName: this.state.firstName,
lastName: this.state.lastName,
age: this.state.age,
email: this.state.email,
description: this.state.description,
hobbies: this.state.hobbies,
location: this.state.location,
};
//x-www-form
let formBody = [];
for (let property in user) {
let encodedKey = encodeURIComponent(property);
let encodedValue = encodeURIComponent(user[property]);
formBody.push(encodedKey + "=" + encodedValue);
}
formBody = formBody.join("&");
console.log(formBody);
axios.post(`http://localhost:8000/users`, { formBody }, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } })
.then(res => {
console.log(res);
console.log(res.data);
})
}
render() {
return (
<div className="register">
<h2>Register</h2>
<form onSubmit={this.handleSubmit}>
<label htmlFor="firstName">First Name:</label>
<input type="text" id="firstName" name="firstName" onChange={this.handleFirstNameChange} />
<br/>
<label htmlFor="lastName">Last Name:</label>
<input type="text" id="lastName" name="lastName" onChange={this.handleLastNameChange} />
<br/>
<label htmlFor="email">Email:</label>
<input type="text" id="email" name="email" onChange={this.handleEmailChange} />
<br/>
<label htmlFor="age">Age:</label>
<input type="text" id="age" name="age" onChange={this.handleAgeChange} />
<br/>
<label htmlFor="description">Description of myself:</label>
<input type="text" id="description" name="description" onChange={this.handleDescriptionChange} />
<br/>
<label htmlFor="hobbies">Hobbies:</label>
<input type="text" id="hobbies" name="hobbies" onChange={this.handleHobbiesChange} />
<br/>
<label htmlFor="location">Location:</label>
<input type="text" id="location" name="location" onChange={this.handleLocationChange} />
<br/>
<input type="submit" value="Register" />
</form>
</div>
);
}
}
export default Register;
{
"_id": {
"$oid": "5b3af97a10d5b622289ddbbc"
},
"firstName": null,
"lastName": "test",
"age": "222",
"photo": null,
"email": "test@gmail.com",
"description": "test",
"hobbies": "test",
"location": "test\"}"
}
有一个URLSearchParams类用于此:
const params = new URLSearchParams();
params.append('param1', 'value1');
params.append('param2', 'value2');
axios.post('/foo', params);
你可以像下面这样修改你的代码,你可以在库的帮助下最小化你的代码,比如
//nodejs路由
从“下划线”导入;
app.post('/users',(req,res)=>{
//const user={firstName:req.body.firstName,lastName:req.body.lastName,age:req.body.age,photo:req.body.photo,email:req.body.email,description:req.body.description,业余爱好:req.body.cabiods,location:req.body.location};
const user=uu.pick(请求正文,'firstName','lastName','email','age','description','cabiods','location')
db.collection('users').insert(user,(err,result)=>{
如果(错误){
res.send({'error':'发生错误'});
}否则{
res.send(result.ops[0]);
}
});
});
//反应注册
从“React”导入React,{Component};
从“axios”导入axios;
类寄存器扩展组件{
状态={
名字:'',
姓氏:“”,
年龄:'',
电子邮件:“”,
说明:“”,
爱好:'',
位置:“”,
};
handleChange=事件=>{
const{name,value}=event.target//对当前字段名称和值进行解构
this.setState({[name]:value});//设置状态
};
handleSubmit=事件=>{
event.preventDefault();
//更改Axios请求,如下所示
axios({
方法:“post”,
网址:'http://localhost:8000/users',
标题:{
“crossDomain”:true,//用于cors错误
“内容类型”:“应用程序/x-www-form-urlencoded”
},
数据:{
名字:this.state.firstName,
lastName:this.state.lastName,
年龄:这个州,
电子邮件:this.state.email,
description:this.state.description,
爱好:这个州,爱好,
地点:this.state.location,
}
})。然后(res=>{
控制台日志(res);
console.log(res.data);
});
}
render(){
返回(
登记
名字:
姓氏:
电邮:
年龄:
自我描述:
业余爱好:
地点:
);
}
}
导出默认寄存器;
当类型为内容类型:'application/x-www-form-urlencoded
时,必须将对象数据解析为字符串urlencoded
在发送之前,您可以使用lib对数据进行字符串化:
const dataSend=qs.stringify(用户)
谢谢你们聪明的回答。我真的很感谢你们的帮助。我还注意到,我的代码的问题是在axios代码中添加{formBody},而不仅仅是没有花括号的formBody。非常棒的答案,谢谢。当我们可以使用axios直接发出请求时,为什么我们要使用axios向node.js服务器发出请求?