我正在构建一个应用程序,它从后端获取数据库中的数据并将数据发送到前端页面。从前端输入所需数据的命令,然后传递到后端,让后端从数据库中获取所需的数据。但是当前端POST命令到后端时,NODE控制台显示:
Error: Can't set headers after they are sent.
前端浏览器控制台显示:
POST http://localhost:5050/ net::ERR_EMPTY_RESPONSE
GET方法运行正常。所以后端和数据库之间的逻辑应该很好,我认为它可能是POST网址的问题?我测试了几个小时仍然无法解决它。请帮忙!提前致谢!
前端代码script.js:
$(document).ready(function() {
var options = {
chart: {
renderTo: containerSpline,
type: 'spline'
},
title: {
text: '信息录入统计曲线图'
},
credits: {
enabled: false
},
xAxis: {
title: {
text: '时间'
},
categories: []
},
yAxis: {
title: {
text: '数量'
}
},
series: []
};
$.get("//localhost:5050", (data)=>{
// feed the data into the chart
var series = {
name:'',
data: []
};
var xAxis = {
categories: []
};
data.recordset.forEach((item)=>{
series.data.push(item.Count);
series.name = item.Dates;
options.xAxis.categories.push(item.Times);
})
options.series.push(series);
var chart = new Highcharts.Chart(options);
})
$('button').click(()=>{
var obj = {
year: $('#year').val(),
month: $('#month').val(),
day: $('#day').val()
}
console.log(obj);
$.post('//localhost:5050',JSON.stringify(obj), (text)=>{
console.log(text);
})
})
})
后端代码fetchData.js:
var express=require('express');
var http = require('http');
var sql=require('mssql');
var fs = require('fs');
var hbs = require('hbs');
var cors = require('cors');
var app=express();
var data;
//config for your database
var config={
user:'elims',
password:'abc123@ksd',
server:'192.168.5.237',
database:'ELIMSDB'
};
//connect to your database
sql.connect(config,function (err) {
if(err) console.log(err);
//create Request object
var request=new sql.Request();
var fDate, lDate;
fDate = '2017-08-04';
lDate = '2017-08-05';
request.input('firstdate', sql.NVarChar, fDate);
request.input('lastdate', sql.NVarChar, lDate);
request.query(" EXEC dbo.KSD_Front_YbidCountByMinutes @firstdate , @lastdate ", (err,recordset) => {
if(err) console.log(err);
//send records as a response
data = JSON.stringify(recordset);
});
});
// send the data to the script.js
app.use(cors());
app.get('/',(req,res)=>{
res.writeHead(200, {'Content-Type':'text/json;charset=utf-8'});
res.end(data);
});
app.post('/', (req, res)=>{
var text = 'Back end response!'
console.log(req.params.obj);
res.writeHead(200, {'Content-Type':'text/json;charset=utf-8'});
res.send(text);
})
app.listen(5050,function(){
console.log('Server is running!');
});