如何使用Node &ExpressJS库进行POST调用。

问题描述 投票:0回答:1

我正在用NodeJS在Express上构建一些自定义的API.我已经成功构建了一些API。使用GET,我能够检索数据。

下面是我的index.js文件和所有的代码。

const express = require('express');
const app = express();

//Create user data.
const userData = [
    {
        id : 673630,
        firstName : 'Prasanta',
        lastName : 'Banerjee',
        age : 24,
        hobby : [
            {
                coding : ['java', 'python', 'javascript'],
                movies : ['action', 'comedy' , 'suspense'],
                sports : "basketball"
            }
        ],
        oper_sys : ['Mac', 'Windows']
    },
    {
        id : 673631,
        firstName : 'Neha',
        lastName : 'Bharti',
        age : 23
    },
    {
        id : 673651,
        firstName : 'Priyanka',
        lastName : 'Moharana',
        age : 24
    },
    {
        id : 673649,
        firstName : 'Shreyanshu',
        lastName : 'Jena',
        age : 25
    },
    {
        id : 673632,
        firstName : 'Priyanka',
        lastName : 'Sonalia',
        age : 23
    },
    {
        id : 673653,
        firstName : 'Bhupinder',
        lastName : 'Singh',
        age : 25
    },
];

//Create the API endpoints with callback functions.
//Display all Employees data.
app.get('/api/employees', function(req, res) {
    res.json(userData);
});

//Display employee data based on 'id' param.
app.get('/api/employees/:id', function(req, res) {
    const id = req.params.id;
    const user = userData.find(user => user.id == id)

    if(user){
        res.statusCode = 200
        res.json(user)
    }
    else {
        res.statusCode = 404
        return res.json({Error: ['ID Not Found']});
    }
});

//start the node server.
const PORT = 7777;
app.listen(PORT, function() {
    console.log('Your server is up & running at localhost:'+PORT+'. Please hit the APIs.');
});

比方说,我想把id:12345 firstName:Michael lastName:Andrews添加到我的userData.How am I supposed to it using POST calls?

我正在寻找可以向我的userData添加新数据的代码,这样每次我做GET的时候,我就能得到更新的数据集。

node.js rest express
1个回答
1
投票

为了在请求时发送POST数据,你必须通过请求体传递数据。要做到这一点,你必须安装一个Node.js body解析中间件,叫做 肢体分析器. 请阅读这个来了解如何在你的应用程序上配置这个。

然后,你必须添加POST路由和方法到你的app.js文件。然后通过body解析数据来打路由与。我已经编辑了你的代码,并发布在下面。我已经注释了我添加方法和中间件的地方。

const express = require('express');
const app = express();

// require body parser middleware
const bodyParser = require('body-parser')

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))

// parse application/json
app.use(bodyParser.json())

//Create user data.
const userData = [
    {
        id: 673630,
        firstName: 'Prasanta',
        lastName: 'Banerjee',
        age: 24,
        hobby: [
            {
                coding: ['java', 'python', 'javascript'],
                movies: ['action', 'comedy', 'suspense'],
                sports: "basketball"
            }
        ],
        oper_sys: ['Mac', 'Windows']
    },
    {
        id: 673631,
        firstName: 'Neha',
        lastName: 'Bharti',
        age: 23
    },
    {
        id: 673651,
        firstName: 'Priyanka',
        lastName: 'Moharana',
        age: 24
    },
    {
        id: 673649,
        firstName: 'Shreyanshu',
        lastName: 'Jena',
        age: 25
    },
    {
        id: 673632,
        firstName: 'Priyanka',
        lastName: 'Sonalia',
        age: 23
    },
    {
        id: 673653,
        firstName: 'Bhupinder',
        lastName: 'Singh',
        age: 25
    },
];

//Create the API endpoints with callback functions.
//Display all Employees data.
app.get('/api/employees', function (req, res) {
    res.json(userData);
});

//Display employee data based on 'id' param.
app.get('/api/employees/:id', function (req, res) {
    const id = req.params.id;
    const user = userData.find(user => user.id == id)

    if (user) {
        res.statusCode = 200
        res.json(user)
    }
    else {
        res.statusCode = 404
        return res.json({ Error: ['ID Not Found'] });
    }
});

// POST emplyee data
app.post('/api/employees/', function (req, res) {

    // catch request body data, break it down and assign it to a variable
    // you can just parse req.body as well
    const newUser = {
        id: req.body.id,
        firstName: req.body.firstName,
        lastName: req.body.lastName
    }

    userData.push(newUser);
    res.status(200).json(newUser);
});

//start the node server.
const PORT = 7777;
app.listen(PORT, function () {
    console.log('Your server is up & running at localhost:' + PORT + '. Please hit the APIs.');
});

0
投票
const express = require('express');
const app = express();

//including the body-parser
app.use(express.json()).use(express.urlencoded({ extended: false }));

//Create user data.    

//your get routes     

//post route
app.post('/api/employees',function(req,res) {
  //posted data is available in req.body
  //do any validations if required
  userData.push(req.body);
  res.send("success")
}

//start the node server.
const PORT = 7777;
app.listen(PORT, function() {
    console.log('Your server is up & running at localhost:'+PORT+'. Please hit 
the APIs.');
});

你可以检查快递的post方法 此处


0
投票

这是我的完整代码片段(index.js)如你所见,我创建了一个post call函数,它从'data'const中获取数据并发送给服务器。但它仍然没有工作。

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

//Here we are configuring express to use body-parser as middle-ware.
app.use(bodyParser.urlencoded({ extended: false })); //support encoded bodies.
app.use(bodyParser.json());                          //support json encoded bodies.

//Create user data.
const userData = [
    {
        id : 673630,
        firstName : 'Prasanta',
        lastName : 'Banerjee',
        age : 24,
        hobby : [
            {
                coding : ['java', 'python', 'javascript'],
                movies : ['action', 'comedy' , 'suspense'],
                sports : "basketball"
            }
        ],
        oper_sys : ['Mac', 'Windows']
    },
    {
        id : 673631,
        firstName : 'Neha',
        lastName : 'Bharti',
        age : 23
    },
    {
        id : 673651,
        firstName : 'Priyanka',
        lastName : 'Moharana',
        age : 24
    },
    {
        id : 673649,
        firstName : 'Shreyanshu',
        lastName : 'Jena',
        age : 25
    },
    {
        id : 673632,
        firstName : 'Priyanka',
        lastName : 'Sonalia',
        age : 23
    },
    {
        id : 673653,
        firstName : 'Bhupinder',
        lastName : 'Singh',
        age : 25
    },
];

//Create the API endpoints with callback functions.
//Display a message.
app.get('/api/info', function(req, res) {
    res.send('Welcome to Employees API !!! Get access to free APIs.');
});

//Display all Employees data.
app.get('/api/employees', function(req, res) {
    res.json(userData);
});

//Display employee data based on 'id' param.
app.get('/api/employees/:id', function(req, res) {
    //Retrieve the 'id' param from endpoint.
    const id = req.params.id;
    //Search for that 'id' param in the 'userdata'.
    const user = userData.find(user => user.id == id)

    //If found, then display the data to the user.
    if(user){
        res.statusCode = 200
        res.json(user)
    }
    //Else, display error message.
    else {
        res.statusCode = 404
        return res.json({Error: ['ID Not Found']});
        //res.send("Oops !!! No User with ID:" + id + " was found.")
    }
});

const data = [ {
    id : 12345,
    firstName : 'new',
    lastName : 'data',
    age : 29
}]

// POST employee data
app.post('/api/employees/', function (req, res) {
    const newUser = {
        id: req.body.id,
        firstName: req.body.firstName,
        lastName: req.body.lastName
    }

    userData.push(newUser);
});

//start the node server.
const PORT = 7777;
app.listen(PORT, function() {
    console.log('Your server is up & running at localhost:'+PORT+'. Please hit the APIs.');
});

0
投票

假设你在post请求中传递的是json,它将是这样的:你的请求体将是这样的。

{
  "id": "1",
  "firstName": "First Name",
  "lastName": "Last Name"
}
app.post('/api/employees', function(req, res) {
    if(req.body) {
      userData.push(req.body)
    }
    else {
      res.statusCode = 500
      return res.json({Error: ['Object Missing']});
    }
});

0
投票

我考虑你将从任何UI前端或通过Postman推送这些数据,并且你知道如何使用它。下面的解决方案会将数据存储在一个数组中,但对于生产,你必须使用数据库作为持久化数据的解决方案。

由于你没有提到你使用的是哪个版本的Express,我建议首先安装一个叫做 body-parser.

欲了解更多信息。https:/www.npmjs.compackagebody-parser

const bodyParser = require("body-parser"); // require it
    app.use(bodyParser()); // you may also use Express' built-in app.use(express.json()); as an alterative

    app.post('/api/employees', (req, res) => { //ES6 Feature: Arrow Syntax
       const { id, firstName, lastName } = req.body; //ES6 Feature: Object Destructuring
       const newUserData = {
           id, // when playing with arrays, try userData.length + 1 to auto-generate an id. Omit this field then; while passing from UI/Postman
           firstName, // pass a string from the UI/Postman. "Michael" in your case
           lastName // pass a string from the UI/Postman. "Andrews" in your case
        }; // ES6 Feature: Equivalent to {id: id, firstName: firstName, lastName: lastName}
        userData.push(newUserData); // use unshift(); instead of push() if you want to add it at the start of an array
        res.status(201).send(newUserData); // 201 = response code for creation. Instead of send(), json() can also be used.
    });

请注意。我在我的每一行代码中都加入了注释,让你充分理解,对其他人也会有帮助。


0
投票

发送POST数据

您需要指定 接受内容类型 头信息,并在POST请求中对JSON对象进行字符串化。

var userData = {
    id : 42069,
    firstName : 'Bob',
    lastName : 'Ross',
    age : 69
}


fetch('/api/employees', {
  method: 'POST',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(userData)
  })
  .then(res => res.json())
  .then(data => {
    console.log(data);
  })

如何在快递上接收POST

app.post('/api/employees', function (req, res) {
  console.log(req.body);
  //req.body will have your new user data. append that to exsisting userData array

  var newUser = {
    id: req.body.id,
    firstName: req.body.firstName,
    lastName: req.body.lastName,
    age: req.body.age
  }

  userData.push(newUser);
  res.json({status: 'New user added'})
})

你需要全局声明userData数组,或者最好使用数据库。

© www.soinside.com 2019 - 2024. All rights reserved.