最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Post an object with fetch using react js and express API server - Stack Overflow

programmeradmin2浏览0评论

I am getting troubles with the post method in fetch because my server is receiving an empty object from the client. I've checked in the client side and can't send the value that I want to send.

This is my server:

const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const mysql = require('mysql');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: true
}));

// connection configurations
const mc = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: '12345',
    database: 'node_task_demo',
    //socketPath: '/Applications/MAMP/tmp/mysql/mysql.sock'
});

// connect to database
mc.connect();

// default route
app.get('/', function (req, res) {
    return res.send({ error: true, message: 'hello' })
});

// Here where I'm calling in the client side
app.get('/todos', function (req, res) {
    mc.query('SELECT * FROM tasks', function (error, results, fields) {
        if (error) throw error;
        return res.send({ error: false, data: results, message: 'Todo list' });
    });
});

// Search for todos with ‘bug’ in their name
app.get('/todos/search/:keyword', function (req, res) {
  var mensaje = 'Todos search list.';
    let keyword = req.params.keyword;
    mc.query("SELECT * FROM tasks WHERE task LIKE ? ", ['%' + keyword + '%'], function (error, results, fields) {
        if (error) throw error;
        return res.send({ error: false, data: results, message: mensaje});
    });
});

// Retrieve todo with id
app.get('/todo/:id', function (req, res) {

    let task_id = req.params.id;

    if (!task_id) {
        return res.status(400).send({ error: true, message: 'Please provide task_id' });
    }

    mc.query('SELECT * FROM tasks where id=?', task_id, function (error, results, fields) {
        if (error) throw error;
        return res.send({ error: false, data: results[0], message: 'Todos list.' });
    });

});

// Add a new todo
app.post('/todo/meterla', function (req, res) {

    let task = req.body.task;

    if (!task) {
        return res.status(400).send({ error:true, message: 'Please provide task' });
    }

    //var task = req.body.task;

    var query = mc.query("INSERT INTO tasks SET ? ", { task: task}, function (error, results, fields) {
        if (error) throw error;
        console.log(task);
        return res.send({ error: false, data: results, message: 'New task has been created successfully.' });
    });
});

//  Update todo with id
app.put('/todo', function (req, res) {

    let task_id = req.body.task_id;
    let task = req.body.task;

    if (!task_id || !task) {
        return res.status(400).send({ error: task, message: 'Please provide task and task_id' });
    }

    mc.query("UPDATE tasks SET task = ? WHERE id = ?", [task, task_id], function (error, results, fields) {
        if (error) throw error;
        return res.send({ error: false, data: results, message: 'Task has been updated successfully.' });
    });
});

//  Delete todo
app.delete('/todo', function (req, res) {

    let task_id = req.body.task_id;

    if (!task_id) {
        return res.status(400).send({ error: true, message: 'Please provide task_id' });
    }
    mc.query('DELETE FROM tasks WHERE id = ?', [task_id], function (error, results, fields) {
        if (error) throw error;
        return res.send({ error: false, data: results, message: 'Task has been updated successfully.' });
    });
});

// all other requests redirect to 404
app.all("*", function (req, res, next) {
    return res.send('page not found');
    next();
});

// port must be set to 8080 because incoming http requests are routed from port 80 to port 8080
app.listen(8081, function () {
    console.log('Escuchando por el puerto 8081');
});

// allows "grunt dev" to create a development server with livereload
module.exports = app;

This is my client:

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';

class App extends Component {

  constructor(props) {
    super(props);
    this.state = {data: ""};
    this.state_2 = {message: []};
    this.onSubmit = this.handleSubmit.bind(this);
  }

  componentDidMount() {
     fetch('/todo/1')
    .then((response) => response.json())
    .then((responseJson) =>{
      this.setState({
        message: responseJson.data
      });
    })
  }

handleSubmit(e){
  e.preventDefault();
  var self = this;
  // On submit of the form, send a POST request with the data to the server.
  fetch('/todo/meterla',{
    method: 'POST',
    body:{
      task: self.refs.task.value
    }
  })
  .then(function(response){
    return response.json()
  }).then(function(body){
    console.log(body);
    alert(self.refs.task.value)
  });
}

  render() {
    return (
      <div className="App">
        <div className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h2>Welcome to React</h2>
        </div>
        <form onSubmit={this.onSubmit}>
          <input type="text" placeholder="task" ref="task"/>
          <input type="submit"/>
        </form>
        <p className="App-intro">
          Este es el resultado de la consulta = <b>{JSON.stringify(this.state.message)}</b>
        </p>
      </div>
    );
  }
}

export default App;

I am getting troubles with the post method in fetch because my server is receiving an empty object from the client. I've checked in the client side and can't send the value that I want to send.

This is my server:

const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const mysql = require('mysql');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: true
}));

// connection configurations
const mc = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: '12345',
    database: 'node_task_demo',
    //socketPath: '/Applications/MAMP/tmp/mysql/mysql.sock'
});

// connect to database
mc.connect();

// default route
app.get('/', function (req, res) {
    return res.send({ error: true, message: 'hello' })
});

// Here where I'm calling in the client side
app.get('/todos', function (req, res) {
    mc.query('SELECT * FROM tasks', function (error, results, fields) {
        if (error) throw error;
        return res.send({ error: false, data: results, message: 'Todo list' });
    });
});

// Search for todos with ‘bug’ in their name
app.get('/todos/search/:keyword', function (req, res) {
  var mensaje = 'Todos search list.';
    let keyword = req.params.keyword;
    mc.query("SELECT * FROM tasks WHERE task LIKE ? ", ['%' + keyword + '%'], function (error, results, fields) {
        if (error) throw error;
        return res.send({ error: false, data: results, message: mensaje});
    });
});

// Retrieve todo with id
app.get('/todo/:id', function (req, res) {

    let task_id = req.params.id;

    if (!task_id) {
        return res.status(400).send({ error: true, message: 'Please provide task_id' });
    }

    mc.query('SELECT * FROM tasks where id=?', task_id, function (error, results, fields) {
        if (error) throw error;
        return res.send({ error: false, data: results[0], message: 'Todos list.' });
    });

});

// Add a new todo
app.post('/todo/meterla', function (req, res) {

    let task = req.body.task;

    if (!task) {
        return res.status(400).send({ error:true, message: 'Please provide task' });
    }

    //var task = req.body.task;

    var query = mc.query("INSERT INTO tasks SET ? ", { task: task}, function (error, results, fields) {
        if (error) throw error;
        console.log(task);
        return res.send({ error: false, data: results, message: 'New task has been created successfully.' });
    });
});

//  Update todo with id
app.put('/todo', function (req, res) {

    let task_id = req.body.task_id;
    let task = req.body.task;

    if (!task_id || !task) {
        return res.status(400).send({ error: task, message: 'Please provide task and task_id' });
    }

    mc.query("UPDATE tasks SET task = ? WHERE id = ?", [task, task_id], function (error, results, fields) {
        if (error) throw error;
        return res.send({ error: false, data: results, message: 'Task has been updated successfully.' });
    });
});

//  Delete todo
app.delete('/todo', function (req, res) {

    let task_id = req.body.task_id;

    if (!task_id) {
        return res.status(400).send({ error: true, message: 'Please provide task_id' });
    }
    mc.query('DELETE FROM tasks WHERE id = ?', [task_id], function (error, results, fields) {
        if (error) throw error;
        return res.send({ error: false, data: results, message: 'Task has been updated successfully.' });
    });
});

// all other requests redirect to 404
app.all("*", function (req, res, next) {
    return res.send('page not found');
    next();
});

// port must be set to 8080 because incoming http requests are routed from port 80 to port 8080
app.listen(8081, function () {
    console.log('Escuchando por el puerto 8081');
});

// allows "grunt dev" to create a development server with livereload
module.exports = app;

This is my client:

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';

class App extends Component {

  constructor(props) {
    super(props);
    this.state = {data: ""};
    this.state_2 = {message: []};
    this.onSubmit = this.handleSubmit.bind(this);
  }

  componentDidMount() {
     fetch('/todo/1')
    .then((response) => response.json())
    .then((responseJson) =>{
      this.setState({
        message: responseJson.data
      });
    })
  }

handleSubmit(e){
  e.preventDefault();
  var self = this;
  // On submit of the form, send a POST request with the data to the server.
  fetch('/todo/meterla',{
    method: 'POST',
    body:{
      task: self.refs.task.value
    }
  })
  .then(function(response){
    return response.json()
  }).then(function(body){
    console.log(body);
    alert(self.refs.task.value)
  });
}

  render() {
    return (
      <div className="App">
        <div className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h2>Welcome to React</h2>
        </div>
        <form onSubmit={this.onSubmit}>
          <input type="text" placeholder="task" ref="task"/>
          <input type="submit"/>
        </form>
        <p className="App-intro">
          Este es el resultado de la consulta = <b>{JSON.stringify(this.state.message)}</b>
        </p>
      </div>
    );
  }
}

export default App;
Share Improve this question edited Aug 20, 2023 at 8:44 Brian Tompsett - 汤莱恩 5,88372 gold badges61 silver badges133 bronze badges asked Jul 24, 2017 at 19:02 Ramses SernaRamses Serna 1221 gold badge3 silver badges10 bronze badges
Add a comment  | 

5 Answers 5

Reset to default 11

body must be stringified + don't forget the content-type

 fetch('/todo/meterla',{
    method: 'POST',
    body: JSON.stringify({
      task: self.refs.task.value
    }),
    headers: {"Content-Type": "application/json"}
  })
  .then(function(response){
    return response.json()
  }).then(function(body){
    console.log(body);
    alert(self.refs.task.value)
  });

try using axios instead of fetch I rewrote ur code like this and it works perfectly

server

const express     = require('express');
const { Client }  = require('pg');
const bodyParser  = require('body-parser');
const app         = express();
const cors = require("cors");

app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.post('/api/insertUsers', function(req, res) {
// console.log(req);
console.log(req.body);
res.send(req.body);
}); 

app.listen(3001, () => {
 console.log('listening on port 3001');
});

react (ensure you have axios installed)

handleSubmit(e){
e.preventDefault(); var data = { name: "zadiki", contact: "0705578809", email: "zadiki", message: "test", } console.log("wow"); var url = ' http://localhost:3001/api/insertUsers'; axios.post(url,data) .then(response=>console.log(response)) .catch(e=>console.log(e)) }

Looks like this is where the issue is.

constructor(props) {
super(props);
this.state = {data: ""};
this.state_2 = {message: []};
this.onSubmit = this.handleSubmit.bind(this);
}

componentDidMount() {
 fetch('/todo/1')
.then((response) => response.json())
.then((responseJson) =>{
  this.setState({
    message: responseJson.data
  });
})
}

In componentDidMount() you are setting the state for 'message'. But that is in this.state_2.

I would recommend not having this.state_2 and instead constructing your state like this:

this.state = {
  data: '',
  message: []
}

try using fetch like this

     fetch(url, {
        method: "POST",
        mode: "cors",
        cache: "no-cache", 
        credentials: "same-origin", 
        headers: {
            "Content-Type": "application/json; charset=utf-8",
        },
        redirect: "follow", 
        referrer: "no-referrer", 
        body: JSON.stringify(data)
    }).then(function (response) {
        return response.json();
    })
        .then(function (myJson) {
            console.log(myJson);
        });
$(document).ready(()=>{

    $("#formSignUp").submit(()=>{

         fetch("/auth/sign/up",{

            method:'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body:$("#formSignUp").serialize(),
        })
        .then((response)=>response.json())
        .then(response=>{

        }).catch(response=>{

        });
        return false;
    });

});

发布评论

评论列表(0)

  1. 暂无评论