React Native / Laravel - Sending a request to API - json

I'm implementing an mobile application that uses Laravel as an API to communicate with a database.
I want to send a username and password from my react native application to Laravel. I am using the following code to do so:
fetch("mysite.com/api/login", {method: "POST", body: JSON.stringify({username: this.state.username, password: this.state.password})})
.then((response) => response.json())
.then((responseData) => {
this.handleLogin(responseData);
})
.done();
}
But this uses JSON.stringify to send across the data. But how do I handle that inside my Laravel application? Currently, I am accepting the data by:
public function login(Request $request)
{
$username = $request->get('username');
}
However, this is obviously not working since the data being sent is in JSON format. So inside PHP, do I need to decode the JSON parameter?

if you are getting output from postman then there is an issue in the fetching part else try
public function login(Request $request)
{
$username = $request-> username;
}

Related

When I get JSON data through AJAX, Where does the data get stored?

I want to know the place where certain JSON data get stored when it's sent from server to client which exists in the different directory.
I am trying to build simple API which send JSON data from server side(port number:5001) to client side(port number:3000).
What I noticed doing this project is that http header and body is not the place where the JSON to be contained.
If so, how does JSON data get delivered to client side?
I want to know what happen in code-behind.
Following is the code that I wrote to build simple API:
Client side code:
componentDidMount() {
axios.get('localhost:5001')
.then((result) => console.log(result))
.catch((err) => console.log('Error ocurred'));
}
Server side code(ASP.NET Core 2.0):
UserPosts result = new UserPosts();
result.id = 1;
result.Name = "jay";
result.Password = "1004";
result.Content = "This is text from the server";
string json = JsonConvert.SerializeObject(result);
context.Response.ContentType = "application/json;
charset=utf-8";
await context.Response.WriteAsync(json);
I expected that the JSON data named 'result' will be attached to HTTP header or body but it was not. When I checked the raw data of http body on the console, it was just html content. This is the content displayed on the browser:
{"id":1,"Name":"jay","Password":"1004","Content":"This is text from the server"}
as I wrote in the code, I want this data on the console not on the browser view page.
That seems you get error returned form server side . You should firstly Enable Cross-Origin Requests (CORS) in ASP.NET Core
Add CORS to your web api in ConfigureServices :
services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
}));
And enable that in Configure function :
app.UseCors("MyPolicy");
If you have middleware to modify the response in your web api :
app.Run(async (context) =>
{
UserPosts result = new UserPosts();
result.id = 1;
result.Name = "jay";
result.Password = "1004";
result.Content = "This is text from the server";
string json = JsonConvert.SerializeObject(result);
context.Response.ContentType = "application/json; charset = utf - 8";
await context.Response.WriteAsync(json);
});
In client , you could get the result by accessing .data in response :
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
function test(){
axios.get('http://localhost:5001/api/values')
.then(
(result) => console.log(result.data)
)
.catch(
(err) => console.log('Error ocurred')
);
}
</script>

How to retrieve FormData values from Yii 1.1 back-end?

I am building a page in this platform that will require a title and a file. I am using FormData. I've already used it like this with another back-end framework where I appended a string and a file to the FormData:
const data = new FormData();
data.append("title", this.state.title);
data.append("file", this.state.file[0]);
I am using Redux, so this is the action that will communicate with the back-end:
export function createDownloadableForm(data) {
return (dispatch, getState) => {
const { auth: { oauthToken, oauthTokenSecret } } = getState();
return dispatch({
[CALL_API]: {
endpoint: "/api/downloadable-forms",
method: "POST",
headers: {
'xoauthtoken': oauthToken,
'xoauthtokensecret': oauthTokenSecret,
},
body: data,
types: [CREATE_DOWNLOADABLE_FORMS, CREATE_DOWNLOADABLE_FORMS_SUCCESS, CREATE_DOWNLOADABLE_FORMS_FAILURE]
}
})
}
}
But now I need to access this information from the back-end. How do I do it since what I send is not a JSON? How do I recover the appended data in FormData?
public function actionCreate()
{
$request = \Yii::app()->request;
// ?
}
I've done few things to check what was being sent. One,
\Yii::log(json_encode($request));
will display
{"jsonAsArray":true,"enableCookieValidation":false,"enableCsrfValidation":false,"csrfTokenName":"YII_CSRF_TOKEN","csrfCookie":null,"behaviors":[]}
Using getPost and passing the name of the fields do not work either, it is null. getRaw, just in case something else would be shown, shows nothing as well. It is like nothing is being sent, but the code for sending FormData, the way it is, was used before and works.

Retrieve data from database and send it to ajax in laravel

I have laravel project and I want to retrieve data from database and send it to ajax function
this is the code of show ($ip) function
public function show($id)
{
$result = DB::table('radcheck')get();
return ( $result);
//
}
this is the code of ajax which is trying to retrieve data from that function but it can not
$('.edit-user').on('click', function() {
var id=$(this).data('id');
$.ajax({
type: 'GET',
url: '/users/' + id,
data: {
'_token': $('input[name=_token]').val(),
},
success: function(hr_request) {
alert(hr_request['username']);
},
error: function(hr_request) {
alert(hr_request['username']);
}
});
});
there is no data can be retrieving, I think I must send data from controller to ajax using json data, but how can I send it as json data and how can I process this json data into ajax function
It is simple .. you can do it like following :
public function show($id)
{
$result = DB::table('radcheck')->get();
return response()->json(['data' => $result]); // here 'data' is key to access $result in ajax response , it is optional.
}
In the ajax response you can console it using console.log(hr_request.data) and check your data result. Additionally , to access property you need to do hr_request.data.property
Hope it helps , Thanks.

Angular http post not working 1st time, but works on 2nd time

Trying my first angular exercise. Receiving undefined value on 1st time from http post, but 2nd time getting proper response (Edge, Firefox). Thanks!
LoginService (Calls Http post method and returns observable)
login(loginRequest: LoginRequest){
console.log("LoginService.login - userName " + loginRequest.username);
let options = new RequestOptions({ headers: headers });
return this.http.post(this.http_url, loginRequest, options).map( res =>
res.json());
LoginFormComponent (calls service class and convert JSON to typescript object)
onSubmit() {
this.loginSvc.login(this.loginRequest).subscribe(
data => this.loginResponseStr = data,
error => alert(error),
() => console.log('Request completed')
);
var loginResponse = new LoginResponse();
loginResponse.fillFromJSON(JSON.stringify(this.loginResponseStr));
console.log(loginResponse.status);
console.log(loginResponse.statusDesc);
if(loginResponse.status == "SUCCESS"){
this.router.navigate(['/home-page']);
}
Console log
LoginService.login - userName admin main.bundle.js:370:9
undefined main.bundle.js:266:9
undefined main.bundle.js:267:9
Request completed main.bundle.js:263:181
LoginService.login - userName admin main.bundle.js:370:9
SUCCESS main.bundle.js:266:9
VALID USER main.bundle.js:267:9
Request completed main.bundle.js:263:181
Angular server calls are asynchronous, that mean the code wont wait for the server to respond before executing the rest of the code. Such as PHP. So you would not see a blank page waiting for the server to send data. When you want to deal with the respose come from a server call you have to add all the code within the subscribe; that means if this information needed to be passed to another service.
Your code should look like this.
onSubmit() {
this.loginSvc.login(this.loginRequest).subscribe(
data => {
this.loginResponseStr = data
var loginResponse = new LoginResponse();
loginResponse.fillFromJSON(JSON.stringify(data));
console.log(loginResponse.status);
console.log(loginResponse.statusDesc);
if (loginResponse.status == "SUCCESS") {
this.router.navigate(['/home-page']);
}
},
error => alert(error),
() => console.log('Request completed')
);
}

RestEasy - JSON response - From Angular2 client, how to only get JSON Object

I'm new to REST services, I have an Angular2 client calling a RestEasy JAX-RS service. All I am trying to get is a "Hello World" message in JSON format. I was expecting only a JSON object, but I get my response with the following structure:
_body: "{"message":"Hello World!!"}"
headers: t
ok: true
status: 200
statusText: "OK"
type: 2
url: "http://localhost:8080/helloapp/rest/hello/world"
__proto__: ...
My question is, Is that the way it should be?
I mean, I thought I would be able to access the JSON object straight from the response. Something like
this.service.getHello()
.then( result => {
console.log(JSON.parse(result)); //{message: "Hello World"}
this.message = JSON.parse(result).message;
});
But I actually have to get it from _body:
this.service.getHello()
.then( result => {
this.message = JSON.parse(result._body).message;
console.log(this.message);//Hello World
});
Is it a RestEasy configuration thing, is there a way to change that?
Or
Should I consider that I will always have a field _body in my response with my data, and that's the default response structure?
For eventual consideration, here is my backend code:
HelloWorld Service:
#Path("/hello")
#Produces({ "application/json" })
#Consumes({ "application/json" })
public class HelloWorld {
public HelloWorld() {}
#GET
#Path("/world")
public Message getHello(){
return new Message("Hello World!!");
}
}
My RestEasy version is 3.1.1.Final running in Wildfly 10.1.0.Final
What you're getting back is the Response object from the Http request. This is what all Http operations will return. The easiest way to parse the JSON from that is to just call the json() method on it
this.service.getHello()
.then((res: Response) => {
let obj = res.json();
});
If you want the getHello to just return the object without having to parse it (on the calling client), then you can do it inside the getHello method by mapping it (using the Observable.map operation)
getHello() {
this.http.get(..)
.map((res: Response) => res.json())
.toPromise();
}
As peeskillet says above, you're getting back the entire Response from the request, and while sometimes you may want to examine the headers, perhaps to handle the different return conditions (retry or redirect on 4xx or 5xx responses for example), most of the time we assume a successful request and we just want the payload.
Angular2 encourages the use of Observables, so your service might look something like this:
getHello()
{
return this.http.get(http://localhost:8080/helloapp/rest/hello/world)
}
And your component may look something like this:
data: string;
ngOnInit() {
this.service
.getHello()
.map(response => response.json())
.subscribe (
data => {
this.data = data,
},
err => console.log('Error',err),
() => console.log('data',this.data)
);
}
You call the service, which is an http.get() and returns an Observable object, and we use .map to parse the response as JSON, which also returns an Observable, which we subscribe to.
Subscribe has three callback functions,
.subscribe(success, failure, complete)
In the example above on success we assign the payload - data - to this.data, if the subscribe fails, you log the error, and when it completes, we can do whatever we like, but in this case, we log this.data to the console - that's optional, but I log out the results while developing and then strip them out later.