javascript - SyntaxError : JSON. 解析:React 应用程序上 JSON 数据的第 1 行第 1 列出现意外字符

标签 javascript json reactjs api express

我有一个在后端使用express的React应用程序。我尝试通过 fetch 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;

queries/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: unexpected character at line 1 column 1 of the JSON data

我尝试并更改了每个响应和请求以使用 JSON.parse 或 .json,无论如何我都会收到相同的消息。

当我使用浏览器并转到 api channel 时,我会得到一个格式正确的 JSON,其中包含数据库的内容。

api

我错过了什么吗?

编辑:

堆栈跟踪非常小: enter image description here

当我尝试时:

getMessages = () => { fetch('/api/mess') .then(res => console.log(res)); };

我得到这个对象:

enter image description here

最佳答案

问题在于后端位于PORT 3011,并且API调用是从前端对PORT 3000进行的。

我需要有一个代理从前端指向后端端口。

我需要在 client/package.json (Frontend) 内添加这一行:

"proxy": "http://localhost/3011"

关于javascript - SyntaxError : JSON. 解析:React 应用程序上 JSON 数据的第 1 行第 1 列出现意外字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57960377/

相关文章:

javascript - 如何在 jQuery 中选择一系列元素

javascript - 每次单击 loadmore 按钮时,如何将 getJSON 的结果附加到 div 中?

java - 如何在servlet中读取ajax发送的json

java - 如何在反序列化 Pojo 时忽略 JSON 根元素

javascript - 如何在 Docker 中的部署中为 React 应用程序配置获取基本 url?

javascript - 显示更多文字 :response coming in the form of json

php - 如何在 php 中从此 JSON 获取元素

javascript - 'react-router' 不包含名为 'browserHistory' 的导出。来自/src/App.js

javascript - Unlayer EmailEditor 导入 React 会破坏应用程序

php - POST 直到第二次才起作用