【问题标题】:not able to connect my React application to MySql无法将我的 React 应用程序连接到 MySql
【发布时间】:2018-04-18 05:39:18
【问题描述】:

我正在尝试使用 nodejs 将我的 React 应用程序连接到 MySql 数据库,但是在单击提交按钮时它会引发以下错误:

POST http://localhost:3000/login500(内部服务器错误)

无法加载http://localhost:3000/login:请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,不允许访问 Origin 'http://localhost:8080'。响应的 HTTP 状态代码为 500。如果不透明的响应满足您的需求,请将请求的模式设置为“no-cors”以获取禁用 CORS 的资源。

Uncaught (in promise) TypeError: Failed to fetch

下面是我的登录组件和 nodejs 文件的代码。

登录.js:

import React from "react";
import {Header} from './Header';
export class Login extends React.Component{

constructor() {
 super();
 this.state = { user: {} };
 this.onSubmit = this.handleSubmit.bind(this);
}
handleSubmit(e) {
 e.preventDefault();
 //const proxyurl = "https://cors-anywhere.herokuapp.com/";
 var self = this;
 // On submit of the form, send a POST request with the data to the server.
 fetch('http://localhost:3000/login', {
     method: 'POST',
     body: {
       name: self.refs.name,
       job: self.refs.job
     }
   })
   .then(function(response) {
     return response.json()
   }).then(function(body) {
     console.log(body);
   });
}

render(){
return(
  <div>


  <div id="fm">
  <form onSubmit={this.onSubmit} >
    <div >
    <label>
      Username:
      <input id="uname" type="text" placeholder="Name" ref="name"/>
    </label>
    </div>
    <div >
    <label>
      Password:
      <input id="upass" type="password" placeholder="Jo b" ref="job"/>
    </label>
    </div>
    <input id="sub" type="submit" value="Submit" />
  </form>
  </div>
  </div>
);
}
}

Connection.js:

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

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

con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
//var sql = "INSERT INTO users (name, job) VALUES ('e211', 'Highway 37')";
//con.query(sql, function (err, result) {
//if (err) throw err;
//console.log("1 record inserted");
//});
});

app.post('/login', function(req, res) {
// Get sent data.
var user = req.body;
// Do a MySQL query.
var query = con.query('INSERT INTO users SET ?', user, function(err, result)                     
{
// Neat!
});
res.end('Success');
});


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

在运行 Connection.js 时,它会连接到我的数据库,如果我尝试通过在 Connection.js 文件中编写插入语句并运行它来直接插入数据,那么它会插入到数据库中,但如果我尝试单击提交按钮在我的 UI 上,它会引发上述错误。

有人可以告诉我哪里出错并指导我吗?

【问题讨论】:

    标签: mysql node.js reactjs express


    【解决方案1】:

    您需要在服务器上启用 CORS,这是为了避免对您的服务器 API 进行任何不必要的调用

    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();
     });
    
     app.get('/', function(req, res, next) {
     // Handle the get for this route
      });
    
     app.post('/', function(req, res, next) {
     // Handle the post for this route
     });
    

    【讨论】:

    • 谢谢你的工作,但现在我在使用 json 对象传递输入字段的值时遇到错误。这是我得到的错误: Uncaught (in promise) SyntaxError: Unexpected token S in JSON at position 0 Promise denied (async)
    猜你喜欢
    • 1970-01-01
    • 2016-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-10
    • 1970-01-01
    相关资源
    最近更新 更多