Why the port number is cut when angular app call rest service - rest

I have rest service:
http://localhost:3000/api/brands
When I test it from web browser it works well.
I use it in angular service:
var motoAdsServices = angular.module('motoAdsServices', ['ngResource']);
motoAdsServices.factory('Brand', ['$resource', function($resource) {
return $resource('http://localhost:3000/api/:id', {}, {
query: {
method: 'GET',
params: {
id: 'brands'
},
isArray: true
}
});
}]);
When it is call I have error because in reqest URL I don't have port number:
Request URL: http://localhost/api/brands
Why the port numer is is cut? Angular cut it?
In Angular doc is written:
A parametrized URL template with parameters prefixed by : as in /user/:username. If you are using a URL with a port number (e.g. http://example.com:8080/api), it will be respected.
UPDATE
I use angular version 1.0.8 (thank #KayakDave for your attention) but Angular doc applies to version 1.2.

It has a colon and therefore gets stripped, kind of like :id. If you escape it, you should be ok. Try http://localhost\:3000/api/:id instead. You may run into this again in routes or other places.
There is an issue regarding this behavior in case something changes.
Updated: http://localhost\\:3000/api/:id

Because angular intercept the url and consider the :any as a parameter that you should pass to it.
An easy way to hack this is to put \:3000 in your url.
motoAdsServices.factory('Brand', ['$resource', function($resource) {
return $resource('http://localhost:3000\:3000/api/:id', {}, {
query: {
method: 'GET',
params: {
id: 'brands'
},
isArray: true
}
});
}]);

Quick fix for the resource plugin issue:
var fixedTargetUrl = TARGET_URL.replace(/(:\d{4})/, "\\$1");

Related

axios keeps removing question mark for query string

Here's my axios config:
const axiosApi = axios.create({
baseURL: process.env.NEXT_PUBLIC_API_URL
})
axiosApi.interceptors.response.use(
response =>
response
,
error => {
if (error.response.status === 404) {
throw new Error(`404\nService does not exist\n${error.request.path}`)
}
}
)
export async function get(url) {
console.log(url)
return await
axiosApi.get(url, {
crossDomain: true
}).then(response => {
return response?.data
})
}
The problem is that when I try to get /path?key=value, I get the /pathkey=value does not exist error.
While console.log(url) shows me the true URL with the question mark and query string, the response interceptor strips the question mark out and that causes 404.
Any idea why this happens?
This is an Axios bug in v1.0.0
Issue reported here: https://github.com/axios/axios/issues/4999
Fixed in v1.1.0
You should pass the query params like below:
axios.get('/path', { params: { key: value} });
Try limit the version in dependency.
"dependencies": {
"axios": "~0.27.2",
},
may help.
Personally I don't even get why Axios developer decide to do this.
Basically according to HTTP Protocol both path and query parameters is considered URI.
Axios.get() should accept everything that is considered URI to conform with HTTP specifications.
And project which let user input its URL for fetch the data will just broken out of the box.

Sailsjs - Cloud SDK - Blueprint API auto generated routes?

I wonder if it is possible to have the Blueprint API support in Cloud SDK.
But apparently, the generated cloud.setup.js file does not contain blueprint APIs. Just normal routes beginning with /api
It is written in the Cloud.js file :
* ### Basic Usage
*
* var user = await Cloud.findOneUser(3);
*
* var user = await Cloud.findOneUser.with({ id: 3 });
It lets think that it's possible to have auto generated routes to the blueprint APIs like actionModel -> findOneUser, createServer, addToGame, and so on...
Do you know if that is possible ? I don't find a documentation about this.
Thanks
I took original code in rebuild-cloud-sdk.js and created a rcsdk.js with the code below before the actual for (let address in sails.config.routes):
_.each(_.keys(sails.models), model => {
let action = sails.config.blueprints.prefix + sails.config.blueprints.restPrefix + '/' + model;
_.each([['GET', 'find'], ['POST', 'create']], pair => {
endpointsByMethodName[`${pair[1]}${model}`] = {
verb: pair[0],
url: action,
}
});
_.each([['GET', 'findOne'], ['PUT', 'update'], ['DELETE', 'delete']], pair => {
endpointsByMethodName[`${pair[1]}${model}`] = {
verb: pair[0],
url: action,
args: ['id'],
}
});
});
I also asked this question the other day. It is not possible. We need to be explicit here. Blueprint routes is only for quick integration testing with postman. I don't recommend this though. You should not be using postman or auto routes. You should write tests in files so they are permanent.

how to get query parameter in action2 in sails

I dont know how to set up route according to REST for the search request url like this
localhost:1337/system?id=10
After that, how can we get parameter from the above request in action 2 like this
action2(inputs,exits)
I want to follow best practice for web api in sails. Please hint me to solve and recommend any handy documents.
Thanks in advance
For the Actions2 format, you'd use inputs.id, after properly defining the inputs, of course. For more information, consult the documentation on Actions and Controllers. This would need more finishing, but it gets your input and a function. You'd want to add in your exits, and some real logic, of course, and probably some decent descriptions.
module.exports = {
inputs: {
id: {
type: 'number',
required: true
}
},
exits: {
success: { ... },
error: { ... }
},
fn: async function (inputs, exits) {
var myId = inputs.id;
return exits.success(myId);
}
}

How to create static parameters for use in data stores with rest proxy

I have an ExtJS 5.1.2 app that utilizes throughout the app a global config set of parameters defined in app_dir/app/Application.js, that looks like:
launch: function () {
Ext.Loader.setConfig({enabled: true});
// Static parameters
cardioCatalogQT.config = {
mode: 'test', // switch to control use of staging or production server
//protocol: 'https://',
protocol: 'http://',
//host: 'production_server',
//host: 'test_server,
host: '127.0.0.1:5000',
apiGetQ: '/get_query/',
//apiGetQ: '/api/get_query/',
apiWriteQ: '/remote_query_put',
apiReadQ: '/remote_query_get',
//apiMedsMenu: '/api/meds',
//apiMedsMenu: '/meds',
remove: 'none'
};
// TODO - Launch the application
Ext.onReady(function () {
});
}
This way, I only have one place to change the parameters that make up the url in Ajax calls, (in this case protocol, host and apiGetQ, for example give mr the ability to set url = cardioCatalogQT.config.protocol + cardioCatalogQT.config.host + cardioCatalogQT.config.apiGetQ), in one place to change the server address from development -> testing -> production, instead of having to find all references throughout the app.
However, due to the way that the ExtJs loads, I cannot use these config parameters in data stores that use rest proxies, since these stores seem to load before items in the Ext.Loader.
For example, I have the following store:
Ext.define('cardioCatalogQT.store.Diagnoses', {
extend: 'Ext.data.Store',
alias: 'store.Diagnoses',
config:{
model: 'cardioCatalogQT.model.Diagnosis',
storeId: 'Diagnoses',
autoLoad: true,
proxy: {
type: 'rest',
url: 'http://127.0.0.1:5000/menu/diagnoses',
//url: 'http://test_server/menu/diagnoses',
//url: 'https://prod_server/api/menu/diagnoses',
reader: {
type: 'json',
rootProperty: 'menu_test'
}
}
}
});
So, when I change from testing to development environments, for example, I have to explicitly change the n different references for url in my n stores that have rest proxies.
Is there a way to define a config object so that I can use it for these stores? I looked at some examples of a preloader, but this did not seem to have any use cases documented for a global config object, also I had tried implementing a loadmask in a preloader, but it really screwed with the behavior of my app.
I use to do like #Alexander propose, however I'll prefer the singleton way. More ExtJs/MVC like.
So just to complete, I share my version:
/**
* #class
*/
Ext.define("MyApp.config.Config", {
alternateClassName: [
'MyApp.config'
],
singleton: true,
constant: {
// ... whatever constant you need to put here
},
constructor: function() {
var constant = this.constant;
//
// here, if you need to process some stuff
// for example calculate some constant
// which depend of other constant
//
return constant;
}
});
Require in your app
// Be sure to require your class prior
// to your app classes
Ext.define('MyApp.Application', {
extend: 'Ext.app.Application',
requires: [
'Ext.app.*',
// ext stuff ...
'MyApp.config.Config',
// myApp stuff ...
]
// ...
});
Example usage:
Ext.define('MyApp.store.MyStore', {
// ...
proxy: {
type: 'rest',
url: MyApp.config.remoteUrl
}
})
We had similar issues, so we have put our global ConnectionSettings object into a script tag that is in index.html, before Ext.
<script type="text/javascript">
ConnectionSettings = {
...
...
};
</script>
<!-- The line below must be kept intact for Sencha Cmd to build your application -->
<script id="microloader" ...
That way, the object is available wherever we need it in our Ext code.

Sencha Touch: How to build a restful proxy url syntax?

Defined as a model and its associations, I wish the http calls to follow best practices of restful. For example, if I make the call
user.posts();
I wish to run a call http defined as
users/1/posts
If a call is then put on post with id 32 then the url of reference must be
users/1/posts/32
So I want to avoid using the filter property as is the default for a get
/posts.php?filter=[{"property":"user_id","value":1}]
This is because the api rest are already defined and I can not change them.
I would like to build a minimally invasive solution and reading on various forums the best way is to do an ovveride the method buildURL the proxy rest but was not able to retrieve all the data needed to build the final URL. Can anyone give me an example?
thanks
Try the following:
window.serverUrl = "192.168.1.XX"
var service = "login.php"
var dataTosend: {
username:"xx",
password: "yy"
}
var methode:"POST" / "GET"
this.service(service,methode,dataTosend,onSucessFunction,onFailureFunction);
onSucessFunction: function(res) {
alert("onSucessFunction"):
},
onFailureFunction: function(res) {
alert("onFailureFunction"):
},
service: function(svc, callingMethod, data, successFunc, failureFunc) {
Ext.Ajax.request({
scope: this,
useDefaultXhrHeader: false,
method: callingMethod,
url: window.serverUrl + svc,
params: data,
reader: {
type: 'json'
},
failure: failureFunc,
success: successFunc
});
I hope this will solve your problem...