Handling ajax JSONP with React - ajax

I found this post
and tried to make cross domain request with jsonp but failed both on webpack dev server and live server.
Full code
official_ajax.jsx
const UserGist = React.createClass({
getInitialState: function() {
return {
username: '',
login: ''
};
},
componentDidMount: function() {
$.ajax({
url: this.props.serverPath,
dataType: 'jsonp',
cache: false,
success: function(data) {
const title = data[0];
this.setState ({
username:title.title,
login:title.link
});
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.serverPath, status, err.toString());
}.bind(this)
});
},
render:function() {
return (
<div>
{this.state.username} and <a href = {this.state.login}>here</a>
</div>
);
}
});
export default UserGist;
index.jsx
import UserGist from './official_ajax.jsx';
class App extends React.Component {
render () {
return (
<div>
<UserGist serverPath = "http://api.flickr.com/services/feeds/groups_pool.gne?id=807213#N20&lang=en-us&format=json&jsoncallback=?" />
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("app"));
Every time i receive response from server that "connection is not secure".
Every ideas will be greatly appreciated.

I think about that maybe,
it's https And CORS ( Cross-Origin Resource Sharing) Policy violation.
http -> https
live Web server add-header (Cors header added)
reference URL ; http://enable-cors.org/index.html

Related

React Ajax 400 Bad Request on Rails-React

I am trying to send some data over \appointments via POST request on my handleFormSubmit function. But for some reason I am always getting a 400 Bad Request Error:
Here's my Appointments.jsx file:
import React from 'react';
import Appointment from './Appointment';
import AppointmentForm from './AppointmentForm';
import AppointmentsList from './AppointmentsList';
class Appointments extends React.Component {
constructor(props) {
super(props)
this.state = {
appointments: this.props.appointments,
title: 'Put your event title',
appointment_date: 'When would this happen?'
};
this.handleUserInput = this.handleUserInput.bind(this)
}
handleUserInput(obj_value){
this.setState(obj_value);
}
handleFormSubmit(){
let apppointment = {
title: this.state.title,
appointment_date: this.state.appointment_date
};
$.ajax({
type: "POST",
url: '/appointments',
data: { apppointment },
success: function(data){
console.log(data);
}
});
}
render(){
return(
<div>
<AppointmentForm title={this.state.title}
appointment_date={this.state.appointment_date}
onUserInput={this.handleUserInput}
onFormSubmit={this.handleFormSubmit}
/>
<AppointmentsList appointments={this.props.appointments} />
</div>
)
}
}
export default Appointments;
I am not sure yet but I think it has to do something with this code:
$.ajax({
type: "POST",
url: '/appointments',
data: { apppointment },
success: function(data){
console.log(data);
}
});
Any idea what do i need to do in order to fix this?
On the network tab, you must select the post request and then go to the parameters you are sending and check if you are sending the data and if it is the right structure.
This is how it looks like on Chrome there is where you check the data you are sending
Try modifying your handleFormSubmit
handleFormSubmit() {
let apppointment = JSON.stringify({
title: this.state.title,
appointment_date: this.state.appointment_date
})
$.ajax({
url: '/appointments',
type: "POST",
data: apppointment,
contentType: 'application/json'
})
}
meaby you can try with axios instance ajax

How to get latest records without page refresh using Codeigniter and Websocket

Hello I have one registration form of users as soon as user register in next browser tab i will get that registered user details without page refresh for this i got code from github project and tested that which is working perfectly and I have loaded jquery,socket.js file in both pages (data post,retrieving page)as they mentioned in that still i am not getting latest registered users without page refresh ,so please tell me where the code need to be correct.below is my code
code to post data(register users)
$("#submit").click(function(event){
event.preventDefault();
var dataString = {
name : $("#name").val(),
email : $("#wickets").val()
};
$.ajax({
url: "<?= base_url('User/register') ?>",
type: "POST",
data: dataString,
dataType: "json",
cache : false,
success: function (data) {
if (data.success == true) {
var socket = io.connect( 'http://'+window.location.hostname +':3000' );
socket.emit('registered_users', {
name: data.name,
email: data.email
});
}
}, error: function (xhr, status, error) {
alert(error);
},
});
});
code to get name and email of user who have just register by socket
html div tags to print user name and email
<div id="user_name"></div>
<div id="user_email"></div>
script for socket
var socket = io.connect( 'http://'+window.location.hostname+':3000' );
socket.on( 'registered_users', function( data ) {
$( "#user_name" ).prepend( data.name );
$( "#user_email" ).prepend( data.email );
});

CORS not working with React app

I tried to make a request from wikipedia api. Though I use a normal node.js server (localhost) i get this in the console:
XMLHttpRequest cannot load https://en.wikipedia.org/w/api.php?action=query&format=json&prop=pageimages&generator=search&piprop=name|original&pilimit=max&gsrsearch=Horse&gsrlimit=20. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
This is my react component:
import React, {Component} from 'react';
import axios from 'axios';
class WikipediaViewer extends Component {
constructor(props) {
super(props);
this.state = {
data: null
}
}
componentDidMount() {
axios.get('https://en.wikipedia.org/w/api.php?action=query&format=json&prop=pageimages&generator=search&piprop=name|original&pilimit=max&gsrsearch=Horse&gsrlimit=20')
.then(data => {
this.setState({
data: data
});
console.log(data);
})
}
render() {
return (
<h1>HEllo world!</h1>
);
}
}
export default WikipediaViewer
After having issus with the request I add following config options according to the axios documentation:
componentDidMount() {
axios.get({
method: 'get',
url: 'https://en.wikipedia.org/w/api.php?action=query&format=json&prop=pageimages&generator=search&piprop=name|original&pilimit=max&gsrsearch=Horse&gsrlimit=20',
headers: {'X-Requested-With': 'XMLHttpRequest'},
withCredentials: true,
}).then(data => {
this.setState({
data: data
});
console.log(data);
})
}
Result:
GET http://localhost:3000/[object%20Object] 404 (Not Found)
Why am I have to get this error, though I'm working locally. Btw I used the "Allow-Control-Allow-Origin: *" Chrome extension from vitcad as well and it doesn't work.

Send an Authenticated Request

I have an MVC project secured with a asp.net identity:
This is my Login function:
self.login = function () {
event.preventDefault();
if (!$('#formLogin').valid()) {
return false;
}
var loginData = {
grant_type: 'password',
username: self.userName(),
password: self.password()
};
$.ajax({
type: 'POST',
url: '/API/Token',
data: loginData
}).done(function (data) {
// Cache the access token in session storage.
sessionStorage.setItem(tokenKey, data.access_token);
self.authenticate();
//change status of Login button to Logout
self.redirect('Users');
}).fail(showError);
}
self.authenticate = function () {
self.token = sessionStorage.getItem(tokenKey);
var headers = {};
console.log(self.token);
if (self.token) {
headers.Authorization = 'Bearer ' + self.token;
}
$.ajaxSetup({
headers: headers
});
}
That works fine, I get the token successfully and the headers are set up correctly.
The problem is that when I try to send a request- for example:
self.getUsers = function () {
$.get("/API/Users/GetUsers/");
}
I get a 401 error from the server:
"message": "Authorization has been denied for this request."
What am I doing wrong?
According to the official documentation of the jQuery.ajax, use this to set custom headers of each request:
$.ajaxSetup({
beforeSend: function(xhr) {
xhr.setRequestHeader('Authorization', '...');
}
});

Session info lost using React-Router navigating two ajax calls in react components

I am new here. Would like to seek your help for the problem that blocks me several days.
The design is simple. I have a server.js running localhost. It provides a POST (Login to acquire authentication) and a GET method (retrieving json after authentication). The login uses basic authentication to verify email/password of a user. if matches, return status 200 and put the user in the session & response. The following are the server side codes:
//Log user in Server.js
app.post('/session/login', function(req, res) {
var email = req.body.email;
var password = req.body.password;
if ( null == email || email.length < 1
|| null == password || password.length < 1 ) {
res.status(401).send("Wrong username or password");
return;
}
if (email == "xxxxx" && password == "xxxxx") {
var user = new User(email, password);
req.session.user = user;
return res.status(200).send({
auth : true,
user : user
});
}else{
return res.status(401).send("Wrong username or password");
}
});
The Get Method is having a basic auth before server can pass the json back. The following are the codes:
function Auth (req, res, next) {
if(req.session.user){
next();
}else{
console.log("Auth");
res.status(401).send({
flash : 'Please log in first'
});
}
}
app.get('/form/FormFields', Auth, function(req, res) {
fs.readFile(FORMFIELDS_FILE, function(err, data) {
if (err) {
console.error(err);
process.exit(1);
}
res.json(JSON.parse(data));
});
});
Now client side, I have two js files, one is a form to email/password to call Login above, and the other is simply get the form info using ajax in react. The navigation uses React-Router. The following are some codes:
// login.js
var LoginBox = React.createClass({
getInitialState: function () {
return {text: '', data: []};
},
handleLoginSubmit: function (data) {
$.ajax({
url: "https://localhost:3000/session/login",
dataType: 'json',
type: 'POST',
data: data,
success: function(data) {
this.setState({data: data});
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
},
render: function () {
return(
<div className="container">
<LoginForm data={this.state.data} onLoginSubmit={this.handleLoginSubmit} />
<p className="tips">{this.state.text}</p>
</div>
);
}
});
var LoginForm = React.createClass({
contextTypes: {
router: React.PropTypes.object
},
getInitialState: function () {
return {data:0,tittle: 'Login Test',text:''};
},
handleSubmit: function (e) {
e.preventDefault();
var email = this.refs.email.value.trim();
var password = this.refs.password.value.trim();
if (!email || !password) {
this.setState({text:"please input both username and password!"});
return;
}
this.props.onLoginSubmit({email:email,password:password});
this.setState({text:""});
this.refs.email.value = '';
this.refs.password.value = '';
//Routing defined in React-Router
const path = '/form';
this.context.router.push(path);
},
render: function () {
return (
<form className="loginForm" onSubmit={this.handleSubmit}>
<p>{this.state.tittle}</p>
<input type="email" placeholder="Your username" ref="email"/>
<input type="password" placeholder="Your password" ref="password"/>
<input type="submit" value="Login"/>
<p className="tips">{this.state.text}</p>
</form>
)
}
});
//code piece in form.js to call server and get form info
loadFieldsFromServer: function() {
$.ajax({
url: "https://localhost:3000/form/FormFields",
dataType: 'json',
cache: false,
success: function(data) {
this.setState({data: data});
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
},
Eventually, here is my problem. the login is ok, which I can see from network monitoring. I printed the log in server and found user is saved in the session. However when it navigates to form.js, I always retrieve 401 from server code below. from the log, i found user info in the session disappears and hence the following 401 returns.
else{
console.log("Auth");
res.status(401).send({
flash : 'Please log in first'
});
}
Please anybody help take a look at where i am wrong. Many thanks. BTW, just share more info, when I use Postman to simulate two calls to the server. Once I call login first, I can also retrieve form json successfully unless i call logout to clean the user in the session. Just dont know why it does not work in the program.

Resources