简体   繁体   中英

Post Request express: Cannot set headers after they are sent to the client

I'm fairly new to Node.js and I am having some issues. im working on app for learning purposes but i came across this problem Error: Can't render headers after they are sent to the client. i didnt know how to make it work

C:\Users\GameDev\Desktop\Portfolio\reciepe\node_modules\mysql\lib\protocol\Parser.js:437 throw err; // Rethrow non-MySQL errors ^ Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client at ServerResponse.setHeader (_http_outgoing.js:470:11) at ServerResponse.header (C:\Users\GameDev\Desktop\Portfolio\reciepe\node_modules\express\lib\response.js:771:10) at ServerResponse.send (C:\Users\GameDev\Desktop\Portfolio\reciepe\node_modules\express\lib\response.js:170:12) at ServerResponse.json (C:\Users\GameDev\Desktop\Portfolio\reciepe\node_modules\express\lib\response.js:267:15) at C:\Users\GameDev\Desktop\Portfolio\reciepe\routes\route.js:32:20 at Query. (C:\Users\GameDev\Desktop\Portfolio\reciepe\models\orm.js:9:9) at Query. (C:\Users\GameDev\Desktop\Portfolio\reciepe\node_modules\mysql\lib\Connection.js:525:10) at Query._callback (C:\Users\GameDev\Desktop\Portfolio\reciepe\node_modules\mysql\lib\Connection.js:491:16) at Query.Sequence.end (C:\Users\GameDev\Desktop\Portfolio\reciepe\node_modules\mysql\lib\protocol\sequences\Sequence.js:83:24) at Query.ErrorPacket (C:\Users\GameDev\Desktop\Portfolio\reciepe\node_modules\mysql\lib\protocol\sequences\Query.js:90:8)

SQL error: code: 'ER_PARSE_ERROR', errno: 1064, sqlMessage: 'You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near \'NULL, \'dqdd\'\' at line 1', sqlState: '42000', index: 0, sql: 'INSERT INTO authentication(username,password) VALUES NULL, \'dqdd\'' }

here is the database

var mysql = require('mysql');

var con = mysql.createConnection({
  host: "localhost",
  user: "root",
  password: "",
  database:'reciepeapp'
});

module.exports  = con

the ORM

  const con = require('./db')

    const orm = {

      insertOne: function (values, cb) {

 const sqlQuery = "INSERT INTO authentication(username,password)  VALUES ?";
    con.query(sqlQuery, [values],function (err, data) {
      if (err) {
        console.log(err)
        cb(err, null);
      } else {
        cb(null, data);
      }
  });
    },


    }
    module.exports = orm;

here is the route.js

  const express = require('express');
    const app = express()
    const router = express.Router()
    const bcrypt = require('bcrypt');
    bodyParser = require('body-parser');
    app.use(bodyParser.urlencoded({ extended: true }));

    const orm = require('../models/orm')
    router.get('/',(req,res)=>
        res.render('home')
    )
    router.get('/login',(req,res)=>
        res.render('login')
    )
    router.get('/register',(req,res)=>
        res.render('register')
    )
    router.post("/register", function (req, res) {
        values = [
            username = req.body.username,
            password = req.body.password
        ];


        orm.insertOne(values, function(error) {

            if (error) {
                return res.status(401).json({
                    message: 'Not able to add'
                });
            }
            return res.json({
                username: values.username,
                password:values.password

            });
        });
    });
    module.exports = router

index.js

const express = require('express');
const app = express()
const bodyParser = require("body-parser");
const indexRouter = require('./routes/route')
const con = require('./models/db')
con.connect(function(err) {
    if (err) {
      return console.error('error: ' + err.message);
    }

    console.log('Connected to the MySQL server.');
  });
  app.use(bodyParser.urlencoded({ extended: false }));
  app.use(bodyParser.json());
var exphbs  = require('express-handlebars');
console.log(__dirname)
app.use('/',express.static(__dirname + '/public'));
app.engine('handlebars', exphbs());
app.set('view engine', 'handlebars');
app.use('/',indexRouter)
const PORT = 5000;
app.listen(PORT,()=>console.log('it started on 5000'))

May I know what is wrong with my code?

The problem is in your orm file. There the callback is getting called twice(in case err is true/has a value), which in-turn calls the res.json twice. Try changing the below

con.query(sqlQuery, [values],function (err, data) {
    if (err) {
      cb(err, null);
    } else {
      cb(null, data);
    }
});

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