I am new Developer ReactJS, I develop a registration form with ReactJS on FrontEnd, NodeJS on BackEnd and MySQL about the database.
I want to submit register form, when, I test my Backend on Postman, it works well and insert a date on my database such as I get: { "code": 200, "success": "user registered sucessfully" }
My code is below:
import React, { Component } from 'react';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import AppBar from 'material-ui/AppBar';
import RaisedButton from 'material-ui/RaisedButton';
import TextField from 'material-ui/TextField';
import axios from 'axios';
import Login from './Login';
class Register extends Component {
constructor(props) {
super(props);
this.state = {
username: '',
email: '',
password: ''
}
}
ponentWillReceiveProps(nextProps) {
console.log("nextProps", nextProps);
}
handleClick(event, role) {
var apiBaseUrl = "http://localhost:4000/api";
if (this.state.username.length > 0 && this.state.email.length > 0 && this.state.password.length > 8) {
var payload = {
"username": this.state.username,
"email": this.state.email,
"password": this.state.password
}
axios.post(apiBaseUrl + '/register', payload)
.then(function(response) {
console.log(response);
if (response.data.code === 200) {
console.log("registration successfull");
}
else {
console.log("some error ocurred", response.data.code);
}
})
.catch(function(error) {
console.log(error);
});
}
else {
alert("Input field value is missing");
}
}
render() {
return (
<div>
<MuiThemeProvider>
<div>
<AppBar
title="Register"
/>
<TextField
hintText="Enter votre username"
floatingLabelText="Username"
onChange = {(event,newValue) => this.setState({username:newValue})}
/>
<br/>
<TextField
type = "email"
hintText="Email"
floatingLabelText="Email"
onChange = {(event,newValue) => this.setState({email:newValue})}
/>
<br/>
<TextField
type = "password"
hintText="Enter your Password"
floatingLabelText="Password"
onChange = {(event,newValue) => this.setState({password:newValue})}
/>
<br/>
<RaisedButton label="Submit" primary={true} style={style} onClick={(event) => this.handleClick(event)}/>
</div>
</MuiThemeProvider>
</div>
);
}
}
const style = {
margin: 15,
};
export default Register;
My package.json is :
{
"name": "frontend",
"version": "0.1.0",
"private": true,
"devDependencies": {
"react-scripts": "0.8.5"
},
"dependencies": {
"axios": "^0.15.3",
"material-ui": "^0.20.0",
"react": "^16.2.0",
"react-dom": "^16.2.0",
"react-dropzone": "^3.10.0",
"react-file-tree": "0.0.8",
"react-router-dom": "^4.0.0",
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
},
"proxy": "http://localhost:4000/"
}
When I run my frontend, I get :
xhr.js:175 OPTIONS http://localhost:4000/api//register 0 ()
dispatchXhrRequest @ xhr.js:175
xhrAdapter @ xhr.js:12
dispatchRequest @ dispatchRequest.js:52
Promise.then (async)
request @ Axios.js:57
Axios.(anonymous function) @ Axios.js:77
wrap @ bind.js:9
handleClick @ Register.js:33
onClick @ Register.js:93
EnhancedButton._this.handleClick @ EnhancedButton.js:146
callCallback @ react-dom.development.js:542
invokeGuardedCallbackDev @ react-dom.development.js:581
invokeGuardedCallback @ react-dom.development.js:438
invokeGuardedCallbackAndCatchFirstError @ react-dom.development.js:452
executeDispatch @ react-dom.development.js:836
executeDispatchesInOrder @ react-dom.development.js:858
executeDispatchesAndRelease @ react-dom.development.js:956
executeDispatchesAndReleaseTopLevel @ react-dom.development.js:967
forEachAccumulated @ react-dom.development.js:935
processEventQueue @ react-dom.development.js:1112
runEventQueueInBatch @ react-dom.development.js:3607
handleTopLevel @ react-dom.development.js:3616
handleTopLevelImpl @ react-dom.development.js:3347
batchedUpdates @ react-dom.development.js:11082
batchedUpdates @ react-dom.development.js:2330
dispatchEvent @ react-dom.development.js:3421
Register.js:53 Error: Network Error
at createError (createError.js:15)
at XMLHttpRequest.handleError (xhr.js:87)
How can I fix it please ?
I am new Developer ReactJS, I develop a registration form with ReactJS on FrontEnd, NodeJS on BackEnd and MySQL about the database.
I want to submit register form, when, I test my Backend on Postman, it works well and insert a date on my database such as I get: { "code": 200, "success": "user registered sucessfully" }
My code is below:
import React, { Component } from 'react';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import AppBar from 'material-ui/AppBar';
import RaisedButton from 'material-ui/RaisedButton';
import TextField from 'material-ui/TextField';
import axios from 'axios';
import Login from './Login';
class Register extends Component {
constructor(props) {
super(props);
this.state = {
username: '',
email: '',
password: ''
}
}
ponentWillReceiveProps(nextProps) {
console.log("nextProps", nextProps);
}
handleClick(event, role) {
var apiBaseUrl = "http://localhost:4000/api";
if (this.state.username.length > 0 && this.state.email.length > 0 && this.state.password.length > 8) {
var payload = {
"username": this.state.username,
"email": this.state.email,
"password": this.state.password
}
axios.post(apiBaseUrl + '/register', payload)
.then(function(response) {
console.log(response);
if (response.data.code === 200) {
console.log("registration successfull");
}
else {
console.log("some error ocurred", response.data.code);
}
})
.catch(function(error) {
console.log(error);
});
}
else {
alert("Input field value is missing");
}
}
render() {
return (
<div>
<MuiThemeProvider>
<div>
<AppBar
title="Register"
/>
<TextField
hintText="Enter votre username"
floatingLabelText="Username"
onChange = {(event,newValue) => this.setState({username:newValue})}
/>
<br/>
<TextField
type = "email"
hintText="Email"
floatingLabelText="Email"
onChange = {(event,newValue) => this.setState({email:newValue})}
/>
<br/>
<TextField
type = "password"
hintText="Enter your Password"
floatingLabelText="Password"
onChange = {(event,newValue) => this.setState({password:newValue})}
/>
<br/>
<RaisedButton label="Submit" primary={true} style={style} onClick={(event) => this.handleClick(event)}/>
</div>
</MuiThemeProvider>
</div>
);
}
}
const style = {
margin: 15,
};
export default Register;
My package.json is :
{
"name": "frontend",
"version": "0.1.0",
"private": true,
"devDependencies": {
"react-scripts": "0.8.5"
},
"dependencies": {
"axios": "^0.15.3",
"material-ui": "^0.20.0",
"react": "^16.2.0",
"react-dom": "^16.2.0",
"react-dropzone": "^3.10.0",
"react-file-tree": "0.0.8",
"react-router-dom": "^4.0.0",
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
},
"proxy": "http://localhost:4000/"
}
When I run my frontend, I get :
xhr.js:175 OPTIONS http://localhost:4000/api//register 0 ()
dispatchXhrRequest @ xhr.js:175
xhrAdapter @ xhr.js:12
dispatchRequest @ dispatchRequest.js:52
Promise.then (async)
request @ Axios.js:57
Axios.(anonymous function) @ Axios.js:77
wrap @ bind.js:9
handleClick @ Register.js:33
onClick @ Register.js:93
EnhancedButton._this.handleClick @ EnhancedButton.js:146
callCallback @ react-dom.development.js:542
invokeGuardedCallbackDev @ react-dom.development.js:581
invokeGuardedCallback @ react-dom.development.js:438
invokeGuardedCallbackAndCatchFirstError @ react-dom.development.js:452
executeDispatch @ react-dom.development.js:836
executeDispatchesInOrder @ react-dom.development.js:858
executeDispatchesAndRelease @ react-dom.development.js:956
executeDispatchesAndReleaseTopLevel @ react-dom.development.js:967
forEachAccumulated @ react-dom.development.js:935
processEventQueue @ react-dom.development.js:1112
runEventQueueInBatch @ react-dom.development.js:3607
handleTopLevel @ react-dom.development.js:3616
handleTopLevelImpl @ react-dom.development.js:3347
batchedUpdates @ react-dom.development.js:11082
batchedUpdates @ react-dom.development.js:2330
dispatchEvent @ react-dom.development.js:3421
Register.js:53 Error: Network Error
at createError (createError.js:15)
at XMLHttpRequest.handleError (xhr.js:87)
How can I fix it please ?
Share Improve this question edited Jul 19, 2018 at 15:13 Ichrak Mansour asked Jul 3, 2018 at 10:39 Ichrak MansourIchrak Mansour 1,95212 gold badges38 silver badges64 bronze badges3 Answers
Reset to default 2As already mentioned - if your backend is on a different port or URL, remember to turn on CORS:
axios.post(apiBaseUrl + '/register', payload, { withCredentials: true })
Also please check what content are you expecting on the server side - by default axios.post
will send the data as JSON (with Content-Type
header set to application/json
), if you're expecting it to be let's say application/x-www-form-urlencoded
then set the Content-Type
header accordingly.
axios.post(apiBaseUrl + '/register', payload, {
headers: { 'Content-Type': 'application/x-www-form-urlencoded'
})
If you are running frontend in a different port, CORS may be the reason. Backend doesn't allow requests ing from frontends which run in a different server or port. To avoid this, you can add this code to your frontend: (Better to include in app.js file to make sure it will work in all scripts)
axios.defaults.withCredentials = true;
Also, you need to add the following code to your NodeJS backend: (Better to include in server.js) (I suppose that you use express framework)
var app = express();
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:YOUR_FRONT_END_PORT');
res.setHeader('Access-Control-Allow-Credentials', true);
res.setHeader('Access-Control-Allow-Methods', ['PATCH', 'POST', 'GET', 'DELETE', 'PUT']);
res.setHeader('Access-Control-Allow-Headers', ['Content-Type']);
res.setHeader('Access-Control-Expose-Headers', ['Content-Type']);
next();
});
You may need the following code as well if you use any custom middleware. In your middleware add:
if (req.method === "OPTIONS") {
return next();
}
But if you do not know what you are doing with these exceptions, please consider using a web server like NGINX in the future.
Not sure, but the way you defined the apiBaseUrl is not correct I guess. Please have a look at it.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745457797a4628568.html
评论列表(0条)