Postingan lainnya
Masalah Cors saat melakukan post di server api nodejs memakai express
Saya memiliki kendala saat mengirim data (post) ke server api di nodejs meski menggunakan module cors, namun jika me-retrieve (get) lancar.
Error : 500 internal server error -> 'Allow-origin blabla' is not allowed. (Ini error tentang cors issue).
Spesifikasi : - Menggunakan reactjs (via create-react-app) - Menggunakan express (via express-generator) - Database menggunakan mysql di phpmyadmin
Kode saya :
1. Signup.jsx (Reactjs/clientside)
import React from 'react';
import ReactDOM from 'react-dom';
import {Container,Form,Button,Input} from 'reactstrap';
import Navigation from 'app/views/templates/Navigation';
import Footer from 'app/views/templates/Footer';
class Signup extends React.Component {
constructor(){
super();
this.state = {
username: '',
email: '',
phone: '',
village: '',
district: '',
province: '',
country: '',
zip_code: '',
password: '',
confirm_password: '',
messgae: ''
}
this.inputValue = this.inputValue.bind(this);
this.submitSignup = this.submitSignup.bind(this);
}
submitSignup(e){
e.preventDefault();
let data = {
username: this.state.username,
email: this.state.email,
phone: this.state.phone,
village: this.state.village,
district: this.state.district,
province: this.state.province,
country: this.state.country,
zip_code: this.state.zip_code,
password: this.state.password,
confirm_password: this.state.confirm_password
}
fetch('/api/users/add',{method:'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(data)})
.then(function(response){
if(response.status >= 400){
console.log(response.status);
}
return response;
})
.then(function(data){
if(data == 'success'){
this.setState({message: 'Thank for registering'});
}
});
}
inputValue(e) {
this.setState({[e.target.name]: e.target.value});
}
render(){
const logo = process.env.PUBLIC_URL+'/assets/img/logo.svg';
return (
<div>
<Navigation/>
<Container fluid style={{marginTop:'58px'}}>
<br/>
<Form className="form-responsive" onSubmit={this.submitSignup}>
<h4 className="blue-light average"><img className="img-md rmargin-sm" src={logo}/>IndoMarket</h4>
<div className="view tmargin-sm bmargin-sm bg-blue-light"></div>
<p className="raleway font-lg text-center margin-md">Daftar dengan</p>
<button type="button" id="oauth-google" className="btn btn-md btn-block btn-default proxima-sb font-md black bmargin-md"><b className="mdi mdi-google-plus font-md rmargin-xs red"></b> Google +</button>
<hr/>
<p className="raleway font-lg text-center margin-md">Atau</p>
<Input type="text" onChange={this.inputValue} name="username" placeholder="Username"/>
<Input type="email" onChange={this.inputValue} name="email" placeholder="Email"/>
<Input type="telp" onChange={this.inputValue} name="phone" placeholder="Phone number"/>
<Input type="password" onChange={this.inputValue} name="password" placeholder="Password"/>
<Input type="password" onChange={this.inputValue} name="confirm_password" placeholder="Confirm password"/>
<br/>
<Button className="bg-blue-light">Submit</Button>
</Form>
<br/>
</Container>
<Footer/>
</div>
);
}
}
export default Signup;
2. App.js (Config express/serverside)
var express = require('express'),
http = require('http'),
mysql = require('mysql'),
connection = require('express-myconnection'),
path = require('path'),
cors = require('cors'),
favicon = require('serve-favicon'),
logger = require('morgan'),
cookieParser = require('cookie-parser'),
bodyParser = require('body-parser'),
stylus = require('stylus'),
mysql = require('mysql'),
fs = require('fs'),
ejs = require('ejs'),
routes,
app = express();
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(stylus.middleware(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));
app.use(cors());
fs.readdirSync('./controllers').forEach(function(file){
if(file.substr(-3) == '.js'){
routes = require('./controllers/'+file.replace(/.js/,''));
routes.controller(app);
}
});
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
app.use(function(err, req, res, next) {
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
3. UsersModel.js (model saya di express/serverside)
var connection = require('../bin/connection');
var readUsers = function(res,position,number_page) {
let limit;
typeof position !== 'undefined' && typeof number_page !== 'undefined' ? limit = ' LIMIT '+position+','+number_page : limit = '';
connection.query(" SELECT * FROM users ORDER BY id_user DESC "+limit,function(err,row,field){
if(err) throw err;
res.send(JSON.stringify({"status": 200, "error": null, "response": row}));
});
};
var readUser = function(res) {
connection.query(" SELECT * FROM users WHERE id_user = ? ",res.id,function(err,row,field){
if(err) throw err;
res.send(JSON.stringify({"status": 200, "error": null, "response": row}));
});
};
var signup = function(res) {
console.log(res);
const data = {username: res.body.username, email: res.body.email, phone: res.body.phone, password: res.body.password, confirm_password: res.body.confirm_password}
connection.query(" INSERT INTO users SET username = '"+res.body.username+"', email = '"+res.body.email+"', phone = '"+res.body.phone+"', password = '"+res.body.password+"', confirm_password = '"+res.body.confirm_password+"'", function(err,row,field){
if(err) throw err;
res.send(JSON.stringify({"status": 200, "error": null, "response": row}));
});
};
module.exports = UsersModel = {
readUsers: readUsers,
signup: signup
};
4. index.js (default route/controller saya diexpress/serverside)
var UsersModel = require('../models/UsersModel'),
cors = require('cors');
var main = function(app){
app.get('/',function(req,res){
let data = {
name: 'Myapp for developer',
description: 'Building great application for indonesia country state with indomarket Api\'s'
}
res.render('index',{title:'Developer',data});
});
app.get('/api/users',function(req,res){
UsersModel.readUsers(res);
});
app.post('/api/users/add',function(req,res){
UsersModel.signup(res);
});
};
module.exports = { controller: main };
Mohon bantuan dan pertolongannya :-) Terima kasih
1 Jawaban:
Sudah berhasil :-) .
Pake :
router.post('/api/users/add',function(req,res,next){
res.header("Access-Control-Allow-Origin","*");
res.header("Access-Control-Allow-Credentials",true);
UsersModel.signup(req,res);
});
dan config express generator di app js dikembalikan seperti defaultnya :-)