简体   繁体   中英

how get data in nodejs received from frontend in reactjs?

I am begineer in reactjs and nodejs , and I think i post data successfully from front end to backend, but now i want to fetch and display received data from frontend in console , but i didnot know how to do it, anyone guide me in this situation? cause when i print something in console like console.log(data) that time it displays some logs in console but i want to display received data in console

demoLogin.js

// this is frontend in reactjs

    import React, { Component } from 'react'
    import axios from 'axios'
    
    class Login extends Component {
    constructor(props) {
      
      super(props)
      
      this.state = {
            username:'',   
            password:''
            
      }
    }
    
    usernameHandler=event=>{
      this.setState({
        username:event.target.value,
        
      })
    }
    passwordHandler=event=>{
      this.setState({
      password:event.target.value
      })
    }
    submitHandler=event=>{
      let data = {
        username: this.state.username,
        password: this.state.password,
        
    };
      event.preventDefault()
            console.log(this.state)
            axios.post('http://localhost:8080/note', data,{
          headers: {'Content-Type':'application/json'}
        })
                .then(res => {
                    console.log(res)
                })
    
        
    }
      render() {
        const {username, password}=this.state
            return (
            <div className="custom_wrapper">
                <div className="custom_form-wrapper">
                  <h1>SIGN IN INTO YOUR ACCOUNT</h1>
                  <form onSubmit={this.submitHandler} >
                    <div className="custom_username" >
                      <label htmlFor="username">User Name</label>
                      <input className='custom_input'
                        placeholder="example@email.com"
                        type="text"
                        name="username"
                        value={username}
                        onChange={this.usernameHandler}
                      /><br></br>
                      
                    
                      <label htmlFor="password">Password</label>
                      <input className='custom_input'
                        placeholder="password"
                        type="password"
                        name="password"
                        value={password}
                        onChange={this.passwordHandler}
                      />
                      <button type="submit" >Login</button>
                    </div>
                    
                    </form>
                    
                </div>
              </div>
            )
        }
    }
    export default Login

server.js

//this is backend in nodejs

    var restify=require('restify')
    const corsMiddleware = require('restify-cors-middleware2');
    const { data } = require('jquery');
    var server=restify.createServer() //server created
    
    server.use(
        function crossOrigin(req,res,next){
          res.header("Access-Control-Allow-Origin", "*");
          res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
          res.setHeader('Access-Control-Allow-Credentials', true); // If needed
          res.header("Access-Control-Allow-Origin", "*");
          res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
          res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
          return next();
        }
      );
    const cors = corsMiddleware({
      preflightMaxAge: 5, //Optional
      origins: ['*'],
      allowHeaders: ['*'],
      exposeHeaders: ['*']
    })
    
    server.pre(cors.preflight)
    server.use(cors.actual)
    server.use(restify.plugins.bodyParser());
    //get data from login form
    function userCreation(req, res, next) {
      console.log('data received...')
      console.log(res.json(data))
      return next();
    }
    
    server.post('/note', userCreation);  
    server.listen(8080, function(){
        console.log("server started...")
    })

Simply create aa GET request to that url you POST ed.


import axios from 'axios'

class App extends Component {
  constructor (props) {
    super(props)
    this.state = {
      username: ''
    }

    this.handleClick = this.handleClick.bind(this)
  }

  handleClick () {
    axios.get('http://localhost:8080/note')
      .then(response => this.setState({username: response.data.name}))
  }

  render () {
    return (
      <div className='show_my__username'>
        <button className='button' onClick={this.handleClick}>Click Me</button>
        <p>{this.state.username}</p>
      </div>
    )
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM