问题描述
我才刚开始MERN Stack,目前正在尝试将数据从RegisterModal.js中的表单发布到server.js
I am just beginning in MERN Stack and am currently trying to POST data from a form located in RegisterModal.js to server.js
index.html文件从index.js获取其内容,该index.js呈现App.js,并根据所单击的按钮呈现不同的组件.(这是我的理解)
The index.html file gets its content from index.js which renders App.js and depending on the button clicked different components are rendered.(This is what I understand)
其中之一是RegisterModal.js,我正在尝试将数据从此表单发布到server.js
One of them being RegisterModal.js, I am trying to post data from this form to server.js
两个文件的代码都位于下面,我的项目结构如下. (其余代码位于github http://github.com/yenvanio/testapp 上)
The code for both files are located below and my project structure is as follows. (The rest of the code is located on github http://github.com/yenvanio/testapp)
我遇到的错误是无法发布到/register",控制台显示找不到错误.
The error I am getting is "Cannot post to /register" and the console gives me a error of not found.
- .idea
- build
- node_modules
- public
- index.html
- server.js
- src
- components
- AdminLoginModal.js
- PopUp.js
- RegisterModal.js
- UserLoginModal.js
- App.js
- index.js
- package.json
代码
server.js
Code
server.js
var express = require('express');
var cors = require('cors');
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var app = express();
var schema = new Schema({
user: [
{
username: String,
password: String,
email: String,
}
]
}, {
collection: 'users'
});
var Model = mongoose.model('Model', schema);
mongoose.connect('mongodb://localhost:27017/dbName');
app.use(bodyParser.urlencoded({
extended:true
}));
app.use(bodyParser.json());
app.post("/register", function(request, response){
var username = request.body.username;
var password = request.body.password;
var email = request.body.email;
console.log("Post Received: %s %s %s", username, password, email);
});
var port = process.env.API_PORT || 3000;
// app.use('/api', router);
app.listen(port, function(){
console.log("Running on port 3000")
})
RegisterModal.js
RegisterModal.js
import React, { Component } from 'react';
class RegisterModal extends Component
{
render() {
return(
<div>
<form method="post" action="/register">
Email Address:<br/>
<input type="text" name="email"/><br/>
Username:<br/>
<input type="text" name="username"/><br/>
Password:<br/>
<input type="password" name="password"/><br/>
<input type="submit" value="Register"/>
</form>
</div>
);
}
}
export default RegisterModal;
推荐答案
您的代码看起来不错.
Your code looks fine.
实际上,我将其复制粘贴,并且可以正常运行.
Actually, I copy pasted it and I can run it without issue.
您确定:
- 您是否已重新启动节点进程(以包括对server.js所做的更改)?
- 节点进程正在侦听HTML页面所加载的域/端口吗?
这篇关于使用React.js和Express.js将表单数据发布到服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!