[英]SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data?
[英]SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data on React app
我有一個在后端使用express的React應用程序。 我嘗試通過提取API調用從數據庫中獲取消息列表。
前端中的代碼:
App.js
getMessages = () => {
fetch('/api/mess')
.then(res => res.json())
.then(res => {
var Messages = res.map(r => r.messages);
this.setState({ Messages });
});
};
后端中的代碼:
api / mess.js
var express = require('express');
var Mess = require('../queries/mess');
var router = express.Router();
router.get('/', (req, res) => {
Mess.retrieveAll((err, messages) => {
if (err)
return res.json(err);
return res.json(messages);
})
});
router.post('/', (req, res) => {
var message = req.body.message;
Mess.insert(message, (err, result) => {
if (err)
return res.json(err);
return res.json(result);
});
});
module.exports = router;
查詢/mess.js
const db = require('../database');
class Mess {
static retrieveAll(callback) {
db.query('SELECT * FROM mess;', (err, res) => {
if (err.error)
return callback(err);
callback(res);
});
}
static insert(mess, callback) {
db.query('INSERT INTO mess (messages) VALUES ($1)', [mess], (err, res) => {
if (err.error)
return callback(err);
callback(res);
});
}
}
module.exports = Mess;
index.js
const path = require('path');
const express = require('express');
const bodyParser = require('body-parser');
var db = require('./database');
const ENV = process.env.NODE_ENV;
const PORT = process.env.PORT || 3011;
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use('/api/mess', require('./api/mess'));
app.use('/api/roles', require('./api/roles'));
app.listen(PORT, () => {
console.log(`Server listening on port ${PORT}...`);
});
module.exports = app;
我在前端收到此錯誤:
SyntaxError:JSON.parse:JSON數據的第1行第1列出現意外字符
我已經嘗試並更改了每個響應和請求以使用JSON.parse或.json,無論如何我都會收到相同的消息。
當我使用瀏覽器並轉到api通道時,會得到帶有數據庫內容的格式正確的JSON。
我錯過了什么?
編輯:
當我嘗試:
getMessages = () => { fetch('/api/mess') .then(res => console.log(res)); };
我得到這個對象:
問題是后端在PORT 3011上,並且從前端對PORT 3000進行了api調用。
我需要有一個代理,以從前端指向后端端口。
我需要在client/package.json
(Frontend)內部添加以下行:
"proxy": "http://localhost/3011"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.