首页 > 解决方案 > 关于连接 React 和 NodeJS express 的问题

问题描述

我试图在 React(Front End) 和 NodeJs(BackEnd) 和 NodeJS -> React(GET) 之间连接,但 React -> NodeJS(POST) 总是出错“POST http://localhost:3001/board/giveresult 500 ( Internal Server Error)”和“Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0” 我一直在解决这个问题,但我被困了一周。问题是什么?

// Method in React

setData() {

        let data = {
            id:this.state.contents.id, //contents is array in the state
            write:this.state.contents.writer,
            title:this.state.contents.title,
            description:this.state.contents.description
        }
    
        fetch('http://localhost:3001/board/giveresult'
        ,{
        method: 'POST',
        headers:{
            'Content-Type':'application/json'
        },
        body:JSON.stringify(data)
        })
        .then (res => res.json())
        .then (data => console.log(data));
    }




//NodeJS Express

const express = require('express');
const app = express();
const receive = require('./routes/receive')
const giveResult = require('./routes/giveResult')
const port = process.env.PORT || 3001;
const cors = require('cors');
var bodyParser = require('body-parser');

app.use(cors());
app.use(bodyParser.json())
app.use('/board/giveresult', giveResult);
app.use('/board/receive', receive);

app.listen(port, function(){
    console.log(`connected ${port} port!`);
});


//giveResult
var express = require('express');
const router = express.Router();
var mysql = require('mysql');
const dbconfig   = require('../mysql.js');
const { Router } = require('express');
const connection = mysql.createConnection(dbconfig);
var bodyParser = require('body-parser');

router.post('/', function(req, res) {
    if(err) throw err;
    
    var post = req.body.id;
    console.log(post)

    res.send('suceess!!!!');
});


module.exports = router;

标签: javascriptmysqlnode.jsreactjs

解决方案


尝试在您的请求标头中添加接受,例如 .

headers: { 
    'Content-Type': 'application/json',
    'Accept': 'application/json'
}

推荐阅读