2017-09-20 54 views
0

我是初學者使用React Js和Node Js,我遇到問題,我無法將我的數據從React Js發佈到Node Js,我一直在尋找方式,但都失敗了,我不知道爲什麼。無法將數據從React Js發佈到Node js

這是我的完整代碼。

這是我的反應文件'member.js',在端口3000(http://localhost:3000/member)上運行。

import React, { Component } from 'react'; 
import ReactDOM from 'react-dom'; 

class Member extends Component { 
    constructor() { 
    super(); 
    this.state = { player: {} }; 
    } 

    handleSubmit(e) { 
    e.preventDefault(); 
    fetch('http://localhost:4000/player', { 
     mode: 'no-cors', 
     method: 'post', 
     headers: { 
      "Content-Type": "text/plain" 
     }, 
     body: JSON.stringify({ 
      number: 123, 
      name: "John", 
      position: "Andrew" 
     }) 
    }).then(function(response) { 
     console.log(response); 
    }).catch(function(error) { 
     console.log('Request failed', error) 
    });  
    } 

    render() { 
    return (
     <div className="member-page"> 
     <form> 
      <input type="submit" onClick={this.handleSubmit.bind(this)} /> 
     </form> 
     </div> 
    ) 
    } 
} 
export default Member; 

,這是我的節點文件 'player.js',在端口4000(http://localhost:4000/player)運行。

var http = require('http'); 
var mysql = require('mysql'); 
var express = require('express'); 
var app = express(); 

var connection = mysql.createConnection({ 
    host: "localhost", 
    user: "root", 
    password: "", 
    database: "react_1" 
}); 

app.post('/player', function(req, res, next) { 

    res.header("Access-Control-Allow-Origin", "*"); 
     res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); 
     next(); 

    var player = req.body; 
    var query = connection.query('INSERT INTO player VALUES ?', player, function(err, result) { 
    // Neat! 
    }); 
    res.end('Success'); 
}); 

app.listen(4000, function() { 
    console.log('Example app listening on port 4000!'); 
}); 

我不知道我做了一個錯誤,請人糾正我的代碼,通過member.jsplayer.js

非常感謝您的幫助。

+0

糾正我,如果我錯了,但我懷疑問題是服務器只在CORS被啓用時才接受,並且在你的客戶端您的請求沒有啓用...我不是這方面的專家,但我試圖幫助 – buoyantair

+0

在控制檯中看到的錯誤是什麼 –

+0

不要將「text/plain」設置爲內容類型if你正在發送JSON數據,並確保你的服務器正在使用['body-parser'](https://www.npmjs.com/package/body-parser)來解析發佈的數據。 – robertklep

回答

0
const express = require('express') 
var bodyParser = require('body-parser') 
const app = express() 
var router = express.Router(); 
router.use(bodyParser.json());  // to support JSON-encoded bodies 
router.use(bodyParser.urlencoded({  // to support URL-encoded bodies 
    extended: true 
})); 

app.get('/', (req, res) => { 
    res.send('Hello World!') 
}) 

app.listen(5000,() => { 
    console.log('Example app listening on port 5000!') 
}) 

app.use('/', router); 

嘗試配置您的節點服務器這樣

+0

我嘗試了你的建議,但是當我嘗試'console.log(req.body)'時,在控制檯顯示未定義,接下來是什麼。 。? –

0

我@robertklep同意。我認爲問題在於var player = req.body;

嘗試:

安裝體解析器 NPM包

npm i -S body-parser 

配置體解析器

var http = require('http'); 
    var mysql = require('mysql'); 
    var express = require('express'); 
    var bodyParser = require('body-parser'); 
    var app = express(); 

    app.use(bodyParser.json()); // for parsing application/json 
    app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded 

    //enable CORS 
    app.use(function(req, res, next) { 
    res.header("Access-Control-Allow-Origin", "*"); 
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); 
    next(); 
    }); 

    var connection = mysql.createConnection({ 
     host: "localhost", 
     user: "root", 
     password: "", 
     database: "react_1" 
    }); 

    app.post('/player', (req, res) => { 
     var player = req.body; 
     var query = connection.query('INSERT INTO player VALUES ?', player, (error, results, fields) => { 
      if (error) throw error; 
      // Neat! 
     }); 
     res.send('Success'); 
    }); 

    app.listen(4000, function() { 
    console.log('Example app listening on port 4000!'); 
    }); 
+0

我嘗試了你的建議,但是當我嘗試'console.log(req.body)'時,在控制檯顯示未定義,接下來是什麼。 。? –

+0

@JohnAndrew我在**/player **路徑之外移動了CORS相關的代碼,並創建了一個[express expressware](http://expressjs.com/en/guide/using-middleware.html)。此外,我將res.end('Success')'改爲'res.send('Success')',因爲res.send使用content-type:text/html作爲Content-Type。讓我知道它是否有效。 –

+0

非常感謝喲@Md Zahidul伊斯蘭教 –