我正在创建一个基本的React应用程序,该应用程序正在从连接到Azure数据库的express.js后端服务接收数据。
我过去创建过express.js后端服务,它一直运行良好,但是React这次没有正确读取json字符串。
Express.js代码
var sql = require('mssql');
var sqlConfig = {
user: 'xxxx',
password: 'xxxx',
server: 'xxx.database.windows.net', // don't add tcp & port number
database: 'xxx',
options: {
encrypt: true
}
};
router.get('/foglamps', function(req, res, next) {
(async function () {
try {
console.log("sql connecting......")
let pool = await sql.connect(sqlConfig)
let result = await pool.request()
.query("GetFogLamps") // subject is my database table name
console.log("Fog Lamps: " + result.recordset[0].fogLampCount)
/* Send data back to user requesting */
//
res.setHeader('Content-Type', 'application/json');
res.json({fogLampCount: result.recordset[0].fogLampCount});
res.send();
sql.close();
} catch (err) {
console.log(err);
}
})()
反应
我能够在Web浏览器和Postman中查看返回的JSON,它看起来像:
{“ fogLampCount”:12960}
我收到以下错误: 未处理的拒绝(SyntaxError):JSON中位置0的意外令牌<< / p>
如果我用有效的已知API替换获取,则可以正常工作。
感谢您的帮助。谢谢。
class Dashboard extends Component {
constructor(){
super();
this.state = {
data: null,
chartData:{},
fogLampsOrdered: 120000,
fogLampsPending: 500000,
fogLampsCompleted: 48000,
defectedFogLamps: 150,
ordersCompleted: 50,
fogLampCount: 0,
rawData: 0,
}
}
componentWillMount(){
this.getChartData();
}
componentDidMount() {
//fetch('https://secure.toronto.ca/cc_sr_v1/data/swm_waste_wizard_APR?limit=1000')
fetch('/users/foglamps')
//Complete promise to receive body text as JSON object
.then(res => res.json())
//Add JSON object to rawData array in state
.then(rawData => this.setState({rawData}));
};