通过邮递员api节点js发布请求时出错

时间:2020-03-14 13:08:33

标签: node.js postman

我是node js的新手,我只想将数据插入到MYSQL数据库中,我搜索了google并找到了此代码。

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

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

//create database connection
const conn = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: '',
  database: 'auth'
});

//connect to database
conn.connect((err) =>{
  if(err) throw err;
  console.log('Mysql Connected...');
});

//add new product
app.post('/add',(req, res) => {
  let data = {name: req.body.name, email: req.body.email, password: req.body.password, contact: req.body.contact};
  let sql = "INSERT INTO registration SET ?";
  let query = conn.query(sql, data,(err, results) => {
    if(err) throw err;
    res.send(JSON.stringify({"status": 200, "error": null, "response": results}));
  });
});

//Server listening
app.listen(3000,() =>{
  console.log('Server started on port 3000...');
});

但是当我尝试调用此api或命中此api时(我不知道在这种情况下要使用的确切字词)我正在以html形式获得响应,这是我得到的错误。 / p>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <title>Error</title>
</head>

<body>
    <pre>Cannot POST /add/</pre>
</body>

</html>

我已经对邮递员进行了更改,例如:

header content-type下的

application/json

这是我要发送的正文或数据

{ 
    "name": "Ayush",
    "email": "ayush@a.com",
    "password": "test",
    "contact": 1234567890
}

1 个答案:

答案 0 :(得分:0)

感谢Sudharsan Selvaraj

我做了一个很小的更改,然后就起作用了,我所做的只是在/之后添加add

app.post('/add/',(req, res) => {
  let data = {name: req.body.name, email: req.body.email, password: req.body.password, contact: req.body.contact};
  let sql = "INSERT INTO registration SET ?";
  let query = conn.query(sql, data,(err, results) => {
    if(err) throw err;
    res.send(JSON.stringify({"status": 200, "error": null, "response": results}));
  });
});