http post request to api nativescript vue - http

Hello I need help with http post request to my server and get response with authentication.
Look on the screens on 1 I use insomnia REST API application. Using this app I got success response with premium days and id.
In second image I got response just from my nativescript vue.js app where I got false response.
There is something wrong with my code. please tell me what.

You are sending a JSON object in your request body from {N} app, on the other hand you are using FormData with your REST client for testing.
You must either change your API to support JSON data on request body which is generally the standard way. In case if you can't do that, then you must use the nativescript-background-http plugin to send FormData. It will be something like,
var params = [
{ name: "username", value: "test" },
{ name: "password", value: "test123" },
{ name: "uuid", value: "xxxx" }
];
var task = session.multipartUpload(params, request);

Related

Creating new document with Firestore REST API and Local Emulator Suite, Returning Error 404: Problem with Path Parameter

I’m just getting acquainted with Firebase/Firestore as a beginner coder, and I'm attempting to create an integration test for a set of callable functions a friend had written for their project. I am writing a test to automate testing using the Firebase local emulator suite.
Right now, I'm attempting to write a POSt request using Axios that will create a document in a given collection in my local emulator suite, after having received an Id Token from generating an authorized user.
The project id is called okane-crud-dev. I’ve created a collection
called test.
I have created an authenticated user with a given email and password, and generated the unique Id Token from an initial post request:
interface createPostRequest {
url: string;
data: Object;
config: Object;
};
//create an instance of a user
const createUserInstance : createPostRequest = {
url: 'http://localhost:9099/identitytoolkit.googleapis.com/v1/accounts:signUp?key=hi',
data: {
'email': 'myemail#email.com',
'password': 'mypassword',
'returnSecureToken': true
},
config: {
'headers':
{'Content-Type': 'application/json'}
},
};
const createUserResponse = await axios.post(createUserInstance.url, createUserInstance.data, createUserInstance.config);
const userIdToken = createUserResponse.data.idToken;
const userLocalId = createUserResponse.data.localId;
Up to this point, I have had no issues.
As for the second POST request to create a document, this is my code. I used this post as a reference:
Creating new collection and document with Firestore REST API returning HTTP 400
const createDocumentInstance : createPostRequest = {
url: "https://firestore.googleapis.com/v1beta1/projects/'localhost:8080/okane-crud-dev'/databases/(default)/documents/test",
data: {
"fields": {
"localId": userLocalId,
'budget': '2000',
}
},
//directly pasted IdToken as using the variable resulted in problem with ' ' error
config: {
'headers':
{
'Content-Type': 'application/json',
'Authorization': `Bearer ${userIdToken}`,
}
}};
console.log(createDocumentInstance);
const createDocument = await axios.post(createDocumentInstance.url, createDocumentInstance.data, createDocumentInstance.config);
const docReference = createDocument.data;
console.log(docReference);
When I attempted to run this, the following error was returned:
Request failed with status code 404
at createError (../../node_modules/axios/lib/core/createError.js:16:15)
at settle (../../node_modules/axios/lib/core/settle.js:17:12)
at IncomingMessage.handleStreamEnd (../../node_modules/axios/lib/adapters/http.js:293:11)
I'm a beginner and am just starting to learn how to code, so bear with me if this is an easy answer as I'm still figuring out how to debug.
I know that a 404 error means an issue with locating the resource -> and after making some adjustments to the headers, I figured the issue must be in my URL. I’ve tried looking around for other posts that use local emulator suite and POST requests to figure out if there was something wrong with how I wrote the path.
"https://firestore.googleapis.com/v1beta1/projects/'localhost:8080/okane-crud-dev'/databases/(default)/documents/test"
I've been looking at the Firebase documentation closely for creating a document; https://firebase.google.com/docs/firestore/reference/rest/v1beta1/projects.databases.documents/createDocument#path-parameters
Borrowing from the other post, I’ve tried different variations of where to include the emulator suite port: localhost:8080 and the project id “okane-crud-dev”. But haven’t seemed to figure out. I made sure that the project id was connected to my local emulator suite. Does anyone have any suggestions?
If you're using the Firestore Emulator with the REST API, you should change the base URL https://firestore.googleapis.com/v1 to your localhost http://localhost:8080/v1 then proceed with the path of your Firestore database.
http://localhost:8080/v1/projects/okrane-crud-dev/databases/(default)/documents/test

How to invoke a SignalR Core hub method from Postman WebSocket

I have a SignalR Core 5.0 app that works in Visual Studio 2019. I will deploy the SignalR server to IIS but want to do some testing in Postman using the new WebSockets.
Taking one of my hub methods in my VS project, let's call it "SomeHubMethod" that returns some data, what is the proper syntax to invoke the hub method?
For instance, how would I translate this C# invoke for Postman WebSocket?
SomeHubMethod = The hub method
groupxyz = The name of the client originating the call to SignalR server, and so the response from the server should be sent to "groupxyz". Let's say the response is "Hello World!"
"1234" = Just some test data.
In my VS project...
private async void SendSomeHubMethod()
{
await connection.InvokeAsync("SomeHubMethod", "groupxyz", "1234");
}
Where the response would be received in my class...
connection.On<string>("TheHubResponse", (m) =>
{
_ = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => Debug.WriteLine(m));
// Hello World!
});
My assembled request that I found in link below for Postman WebSocket...
{"arguments":["groupxyz", "1234"],"invocationId":"0","target":"SomeHubMethod","type":1}
On Send, Postman shows Connected but "Hello World!" is not returned from my hub.
I found this post but it is not detailed on invoke.
reference example
You can but it's kinda problematic, so let's start from beginning..
When you have your defined SignalR hub endpoint (ie. wss://localhost:5005/hub/notifications) then
Make a POST request to following URL (notice the https, not the wss): https://localhost:5005/hub/notifications/negotiate?negotiateVersion=1.
In answer you will receive following information:
{
"negotiateVersion": 1,
"connectionId": "zJ1cqyAe4FRyLCGMzzC0Fw",
"connectionToken": "HYunLu0j0IHdBY4NNrkm0g",
"availableTransports": [
{
"transport": "WebSockets",
"transferFormats": [
"Text",
"Binary"
]
},
{
"transport": "ServerSentEvents",
"transferFormats": [
"Text"
]
},
{
"transport": "LongPolling",
"transferFormats": [
"Text",
"Binary"
]
}
]
}
Get the connectionToken from the step above and copy it. Now open a websocket connection with your hub like following:
wss://localhost:5005/hub/notifications?id={connectionToken} where connectionToken is the token from previous step. The url should look like: wss://localhost:5005/hub/notifications?id=HYunLu0j0IHdBY4NNrkm0g.
Now hold something.. according to the Microsoft documentation (https://github.com/dotnet/aspnetcore/blob/main/src/SignalR/docs/specs/HubProtocol.md#overview) we need to send a handshake request with following informations:
{
"protocol": "json",
"version": 1
}
It's hard to achieve by plain text because it needs to ends with a 0xE1 ASCII character, so we need to convert the handshake request with that character to base64 and send it. I did it for you and this string is:
eyJwcm90b2NvbCI6Impzb24iLCAidmVyc2lvbiI6MX0e
Now when we have all these info, let's deep dive into Postman:
Connect to the endpoint:
Just send a request with string I pasted above to this URL with content-type: Binary using Base64.
As you can see, we are receiving message {"type": 6} what means we are connected to the Hub and it's pinging us.
You can now send/receive any messages from your hub:
Now you can change the content-type to JSON and invoke your hub endpoints.
How to invoke a SignalR Core hub method from Postman WebSocket
Short answer, you can't.
Long answer, SignalR is a protocol that requires certain ceremony to start sending and receiving messages. For example, you need an ID in the query string that is generated by the server. Then you need to send the handshake request over the transport before you can start making invocations.

"Handler crashed with error runtime error: invalid memory address or nil pointer dereference", but POSTMAN is ok! Why this happens?

I work with vue and go for frontend and backend respectively. I send post request to my server and get 403 error code message(notAllowed). But in postman I get the objects and is fine.
Vue and Vuex
My axios post request:
const response = await this.$axios.post(`http://localhost:8000/v1/org/${params.organization}/kkms/${params.kkm}/closeShift`,{
headers : {
'token' : this.state.token.value
}});
I know I should also use other properties like 'Content-Type' and etc in headers, but know it works well with only "token" property in the other requests. I want to know whether problem in backend or frontend?
It seems you have a mistake in the axios request.
You are receiving a 403, that means you are not authorized (or sometimes something else, check the comments in the question and down here ).
As can be found in axios docs, the post request looks like this:
axios.post(url[, data[, config]]).
It accepts the config (so the headers) as THIRD parameter, while you are setting it as second parameter. Add an empty FormData object as second param, and just shift your config to the third param.
const fakeData = new FormData();
const response = await this.$axios.post(`http://localhost:8000/v1/org/${params.organization}/kkms/${params.kkm}/closeShift`,
fakeData,
{
headers : {
'token' : this.state.token.value
}
});

Flutter HTTP request with JSON data to a Firebase function

I am currently trying to set up our Firestore database for a Flutter mobile app to take data from a Firebase function and store it into the database. Currently, we are trying to pass an HTTP request to our URI and attach some JSON data to it.
My function is as follows:
exports.testFunction = functions.https.onRequest((request, response) => {
var data = {
name: request.body.name,
age: request.body.age
};
var setDoc = db.collection('users').add(data);
response.json({result: `User ${data.name} at age ${data.age} added.`});
return;
});
Currently, the data can be retrieved when using a web browser and requesting from https://us-central1-[project-name].cloudfunctions.net/testFunction?name=[string]&age=[int]. This also works within our Flutter app, using the entire URL as a single argument with no body. However, when trying a cURL request from the command line:
curl -H 'Content-Type: application/json' -d '{"name": "[string]", "age": [int]}' https://us-central1-[project-name].cloudfunctions.net/testFunction
Hypothetically, the data should be in request.body, but I am getting an error saying the request could not be handled. What exactly is going wrong here?
Later, we want to implement this request in a Dart/Flutter app by attaching the JSON object to the body of the http.post. Is there a missing link in between this process that I'm missing?
The error Request body is missing data means that the payload that's being sent in the request needs to be mapped inside data. It's mentioned here in the docs that the Request body should have a data field.
var data = {
'data':{
name: request.body.name,
age: request.body.age
}
}

Access token request results in 302 in Angular HttpClient

I'm trying to authenticate requests for WordPress rest-api using grant type password. OAuth2 authentication in WordPress is provided by WP OAuth Server plugin.
When I request access token using Postman Chrome app the server responds with expected access token object but the similar request doesn't work in Angular. It gives status 302 and due to xhr redirect to login page, I'm not able to get access token object. I'm using Angular 5.
Here's how I request access token in Angular:
/* Example token url
AuthProvider.TOKEN_URL:
https://www.example-wordpress.com/oauth/token
*/
const body = {
grant_type: 'password',
username: username,
password: password,
};
const headers = new HttpHeaders()
.set('Authorization', 'Basic ' + btoa(AuthProvider.CLIENT_ID + ':' + AuthProvider.CLIENT_SECRET));
this.http.post(AuthProvider.TOKEN_URL, body, { headers: headers });
The above request produces 302 with location header set to:
https://www.example-wordpress.com/login/?redirect_to=https%3A%2F%2Fwww.example-wordpress.com%2Foauth%2Ftoken
And then a xhr GET request is made to above location which responds with HTML of login page and hence no access token is obtained.
The similar POST request for access token in Postman works fine and results in expected access token object but I can't get it to work in Angular.
EDIT
While debugging I generated JavaScript code for access token request from Postman and pasted in console of Chrome after importing jQuery.
The request works as expected in console as well and no redirection occurs. The response is JSON with access token.
Here's the code Postman generated for the POST request:
var settings = {
"async": true,
"crossDomain": true,
"url": "https://example-wordpress.com/oauth/token",
"method": "POST",
"headers": {
"content-type": "application/x-www-form-urlencoded",
"authorization": "Basic M0wzakE3d080VmxxbXB0UUF1dUI5RkxicWxmeE8yR25Zdk4xQmxvbTp4TktTYnJ1Mno5cEp2VDFMbTNGNFhEQm10eDZzUGsya1FqZDg3VmQ2",
"cache-control": "no-cache",
"postman-token": "46339abe-2d1a-1032-f5d8-36e3193d9a81"
},
"data": {
"grant_type": "password",
"username": "my-username",
"password": "my-password",
"client_id": "3L3jA7wO4VlqmptQAuuB9FLbqlfxO2GnYvN1Blom",
"client_secret": "xNKSbru2z9pJvT1Lm3F4XDBmtx6sPk2kQjd87Vd6"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
And here's the response logged from above code:
{
access_token: "rksen3p351fj0povsrpfv2eeuahrciglc3ilphhy",
expires_in: 3600,
token_type: "Bearer",
scope: "basic",
refresh_token: "fudju8tecbnwly2e1xgfv92tykvpsniwkfpvrd7d"
}
I'm unable to figure out why redirection occurs when we request through Angular and not responds with access token JSON.
Any help is appreciated.
access_token (which I imagine is what you expect to have) isn't part of the few headers that Angular is able to read without setting up your server.
Angular only read "basic" headers such as Content-type. This is because of the default CORS configuration that only reads Cache-Control, Content-Language, Content-Type, Expires, Last-Modified and Pragma. When it comes to custom headers, you have to tell your server to expose the headers.
This is done through the Access-Control-Expose-Headers header.
There was no problem at all. It was a very very silly mistake. I apologize.
I was testing with two websites simultaneously and both had similar configuration. The only difference was that one had OAuth plugin installed and other not. So when I tried to authorize the request from Angular with the website which hadn't had OAuth2 plugin installed and so redirected to the login page. The constant set for the AuthProvider.TOKEN_URL was incorrectly set, while when I was testing with other tools I was using correct url.
Anyway, this was all my mistake. It happens sometimes, when you don't take break. :)

Resources