作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试使用 nodejs 将我的 React 应用程序连接到 MySql 数据库,但单击提交按钮时会抛出以下错误:
发布http://localhost:3000/login 500(内部服务器错误)
加载失败http://localhost:3000/login :请求的资源上不存在“Access-Control-Allow-Origin” header 。来源'http://localhost:8080 ' 因此不允许访问。响应的 HTTP 状态代码为 500。如果不透明响应满足您的需求,请将请求的模式设置为“no-cors”以在禁用 CORS 的情况下获取资源。
未捕获( promise 中)类型错误:无法获取
下面是我的登录组件和 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>
);
}
}
连接.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 文件中编写插入语句并运行它来直接插入数据,那么它会插入到数据库中,但如果我尝试单击提交按钮在我的用户界面上它会抛出上述错误。
有人可以告诉我哪里出了问题并指导我吗?
最佳答案
您需要在服务器上启用 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
});
关于mysql - 无法将我的 React 应用程序连接到 MySql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47130500/
我是一名优秀的程序员,十分优秀!