反应js:axios将请求发布到node.js api

时间:2018-07-03 04:51:24

标签: node.js reactjs axios

嗨,我在使用axios发送请求中的所有数据时遇到了一些麻烦。我创建了node.js api,现在我想使用axios从表单发送用户注册数据,并将js作为前端技术进行响应。

我在提交后更新了我的状态,现在我想通过“ Content-Type”发送信息时:“ application / x-www-form-urlencoded”我的名字不是send(null)并且最后一个值是location最后输入“ \”。

我在邮递员中测试了请求,并且效果很好。

有什么建议吗?

我的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;

数据库结果为mLab:

{
    "_id": {
        "$oid": "5b3af97a10d5b622289ddbbc"
    },
    "firstName": null,
    "lastName": "test",
    "age": "222",
    "photo": null,
    "email": "test@gmail.com",
    "description": "test",
    "hobbies": "test",
    "location": "test\"}"
}

3 个答案:

答案 0 :(得分:0)

有一个URLSearchParams类:

const params = new URLSearchParams();
params.append('param1', 'value1');
params.append('param2', 'value2');
axios.post('/foo', params);

答案 1 :(得分:0)

您可以按照以下方式修改代码,可以借助https://underscorejs.org/

这样的库来最小化代码
//nodejs route
import _ from "underscore";
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 };
    const user = _.pick(req.body, 'firstName', 'lastName', 'email', 'age', 'description', 'hobbies', 'location')
    db.collection('users').insert(user, (err, result) => {
        if (err) {
            res.send({ 'error': 'An error has occurred' });
        } else {
            res.send(result.ops[0]);
        }
    });
});

//React Registration    
import React, { Component } from 'react';
import axios from 'axios';

class Register extends Component {
    state = {
        firstName: '',
        lastName: '',
        age: '',
        email: '',
        description: '',
        hobbies: '',
        location: '',
    };

    handleChange = event => {
        const { name, value } = event.target  //Destructure the current fields name and value
        this.setState({ [name]: value });  //Sets state
    };

    handleSubmit = event => {
        event.preventDefault();
        //Alter your Axios request like below
        axios({
            method: 'post',
            url: 'http://localhost:8000/users',
            headers: {
                'crossDomain': true,  //For cors errors 
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            data: {
                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,
            }
        }).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.handleChange} />
                    <br />
                    <label htmlFor="lastName">Last Name:</label>
                    <input type="text" id="lastName" name="lastName" onChange={this.handleChange} />
                    <br />
                    <label htmlFor="email">Email:</label>
                    <input type="text" id="email" name="email" onChange={this.handleChange} />
                    <br />
                    <label htmlFor="age">Age:</label>
                    <input type="text" id="age" name="age" onChange={this.handleChange} />
                    <br />
                    <label htmlFor="description">Description of myself:</label>
                    <input type="text" id="description" name="description" onChange={this.handleChange} />
                    <br />
                    <label htmlFor="hobbies">Hobbies:</label>
                    <input type="text" id="hobbies" name="hobbies" onChange={this.handleChange} />
                    <br />
                    <label htmlFor="location">Location:</label>
                    <input type="text" id="location" name="location" onChange={this.handleChange} />
                    <br />
                    <input type="submit" value="Register" />
                </form>

            </div>
        );
    }
}

export default Register;

答案 2 :(得分:0)

当类型为Content-Type': 'application/x-www-form-urlencoded时,必须将对象数据解析为string urlencoded

您可以在发送前使用lib qs对数据进行字符串化:

  

const dataSend = qs.stringify(user);

import qs from "qs";

    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 };

          const dataSend = qs.stringify(user);

          db.collection('users').insert(dataSend, (err, result) => {
            if (err) { 
              res.send({ 'error': 'An error has occurred' }); 
            } else {
              res.send(result.ops[0]);
            }
          });
        });