receiving a 404 error when I make a post request to api server - server

I've created a custom endpoint for my api server which deletes a single hearing test:
Account.deleteSingleHearingTest = function (req, callback) {
// console.log('accounts.js: deleteSingleHearingTest: are we being reached????', req)
Account.findById(req.accessToken.userId)
.then(account => {
if (!account) {
throw new Error('Cannot find user');
}
console.log('account.js: deleteSingleHearingTest: req.body.hearingTestId N: ', req.body.hearingTestId);
return app.models.HearingTest.updateAll({ accountId: account.id, id: req.body.hearingTestId }, { isDeleted: new Date() });
})
.then(() => {
callback(null);
})
.catch(error => {
callback(error);
});
}
Account.remoteMethod(
'deleteSingleHearingTest', {
http: {
path: '/deleteSingleHearingTest',
verb: 'post'
},
accepts: [
{ arg: 'req', type: 'object', description: 'removes a single hearing test', http: { source: 'req' } }
],
description: 'this is the end point for a single delete',
returns: {}
}
);
I've also updated acls in account.json:
{
"accessType": "EXECUTE",
"principalType": "ROLE",
"principalId": "$authenticated",
"permission": "ALLOW",
"property": "deleteSingleHearingTest"
}
Using Postman, I made a POST request to the server address which looks something like :
https://xxx.xxxxxxxx.com/api/Accounts/deleteSingleHearingTest?access_token=XXXXXXXXXXXXXXXXXKyBdxkwxm5s8TSceMgclvXjjrTnyn3UJWIa
The response I get back on Postman is a 404 with the attached message
"Shared class \"Account\" has no method handling POST /deleteSingleHearingTest?access_token=XXXXXXXXXXXXXXXXXXqAoKyBdxkwxm5s8TSceMgclvXjjrTnyn3UJWIa",
The strange thing is, this method was working two weeks ago when I first created, the only difference was that I was running the server locally.

I needed to restart the server so the new methods could be pulled in. For the 1 person who actually reads this. To restart the server the command is pm2 start all

Related

Loopback - can't show error from controller

I'm new to loopback and I'm trying to return an error from a rest api controller created by cli with
"lb4 controller"
I don't know why Loopback always insert the data in db: what am I doing wrong???
Here is the code
#post('/tavolos', {
responses: {
'200': {
description: 'Tavolo model instance',
content: {'application/json': {schema: getModelSchemaRef(Tavolo)}},
},
},
})
async createTavolo(
#requestBody({
content: {
'application/json': {
schema: getModelSchemaRef(Tavolo, {
title: 'NewTavolo',
exclude: ['id'],
}),
},
},
})
tavolo: Omit<Tavolo, 'id'>,
): Promise<Tavolo> {
if (!Number.isInteger(Tavolo.max) || Tavolo.max > 10) {
throw new HttpErrors.BadRequest( `error text`, );
}
return this.tavoloRepository.create(tavolo);
}
I solved by myself: i just recreated the project (all models, controllers, etc...) and now it works... don't know where the error is.

Loopback 4 - POST request dtasource template

I am having issue to declare POST operation in Loopback 4 datasource file.
My template is as follows:
{
"template": {
"method": "POST",
"url": "https://reqres.in/api/login"
},
"functions": {
"login": []
}
}
My service interface
login(email: string, password: string): Promise<any>;
My Controller
#post('/loginTest')
async testingLogin(
#requestBody({
content: {
'application/json': {
schema: getModelSchemaRef(TestModel, {
title: 'Post',
}),
},
},
})
testModel: TestModel, )
: Promise<any> {
// TEST MODEL CONTAIN JSON OBJECT {email: "" , password: ""}
console.log("Test Model Representation: ", testModel)
try {
var response = await this.loginService.login(testModel.email, testModel.password);
} catch (error) {
console.log("error", error)
}
console.log("Fake POST response", response)
return response;
};
I am using this fake API : https://reqres.in/api/login
I am getting following error:
Test Model Representation: { email: 'string', password: 'string' }
error Error: {"error":"Missing email or username"}
at callback (D:\loginApp\node_modules\loopback-connector-rest\lib\rest-builder.js:541:21)
at D:\loginApp\node_modules\loopback-datasource-juggler\lib\observer.js:269:22
at doNotify (D:\loginApp\node_modules\loopback-datasource-juggler\lib\observer.js:157:49)
at RestConnector.ObserverMixin._notifyBaseObservers (D:\loginApp\node_modules\loopback-datasource-juggler\lib\observer.js:180:5) {
statusCode: 400,
message: '{"error":"Missing email or username"}'
}
Fake POST response undefined
It look like my email and password is not passed ? Thanks for any help.
The login function you defined in the datasource file should match with the service interface. That means it would be something like:
"functions": {
"login": ["email", "password"]
}

Post to a mongoose schema with array of objects

I want to post some data to my mongo database.
However the structure of the schema confuses me about the implementation.
This is the schema:
var GraphSchema = new Schema({
nodes: [{id: String}],
links: [{source:String, target: String}]
});
This is what I've tried so far but it doesn't seem to working:
router.post('/graphs', (req, res) => {
const graph = new Graph();
graph.nodes = [{id: req.body.nodes.id}];
graph.links = [{source: req.body.source, target: req.body.target}];
graph.save((err) => {
if(err) return res.status(500).json({ message: 'internal error' })
res.json({ message: 'saved...' })
})
});
For example I want to achieve something like this as a final result:
{
"data": [
{
"nodes": [
{
"id": "root"
},
{
"id": "input"
},
{
"id": "component"
}
],
"links": [
{
"source": "component",
"target": "root"
}
]
}
]
}
I a testing the operation with Postman
I am in a kind of dead end regarding how to proceed so I hope you can hint me something!
in your creation of the object , creat it like this
router.post('/graphs', (req, res) => {
const graph = new Graph({
nodes:[{id:req.body.nodes.id}],
links:[{source: req.body.source, target: req.body.target}]
}); // you need to include your data inside the instance of the model when you create it that was the problem.. It should work fine now
In your code you don't actually create the array that you have defined in your schema. So tally with your schema like above and then save. below
graph.save((err) => {
if(err) {
res.status(500).json({ message: 'internal error' });
throw err;
}else{
res.send({ message: 'saved...' });
}
})
});
this is the way you have currently posted the question.. so the answer is valid for that, but I assume this should be sufficient enough for you to figure out what was the problem ..

POST vs. GET request differences in Google Analytics API Version 4

Google Analytics v4 API now uses POST requests instead of GET request. And there are no good javascript examples out there yet for me to follow. I'm getting empty object Object { }, but I'm sure that data is there and ViewID is correct!
Any advice on what I am doing wrong? or are there any fully working example that I can follow? Thanks.
requestData = function () {
var url = "https://analyticsreporting.googleapis.com/v4/reports:batchGet?";
var params = {
"reportRequests":[{
"viewId":"12345678",
"dateRanges":[{
"startDate":"yesterday",
"endDate":"today"
}],
"metrics":[{
"expression":"ga:users"
}],
"dimensions": [{
"name":"ga:pagePath"
}]
}]
}
$.ajax({
url: url,
type: "POST",
data: params,
dataType: "json",
success: function(results) {
console.log(results)
},
error: function(xhr, ajaxOptions, thrownError) {
alert('failed');
alert(xhr.status);
alert(thrownError);
}
});
I would highly recommend you use the Google Javascript Client Library to simplify your life greatly. There are plenty of Code Samples using said library:
var DISCOVERY = 'https://analyticsreporting.googleapis.com/$discovery/rest';
// Load the API from the client discovery URL.
gapi.client.load(DISCOVERY).then(function() {
// Call the Analytics Reporting API V4 batchGet method.
gapi.client.analyticsreporting.reports.batchGet( {
"reportRequests":[{
"viewId":"12345678",
"dateRanges":[{ "startDate":"7daysAgo", "endDate":"today"}],
"metrics":[{"expression":"ga:users"}],
"dimensions": [{"name":"ga:pagePath"}]
}]
}).then(function(response) {
var formattedJson = JSON.stringify(response.result, null, 2);
document.getElementById('query-output').value = formattedJson;
}).then(null, function(err) {
// Log any errors.
console.log(err);
});
As for getting jQuery to work, a similar question was asked about nodejs Their solution was to set the content-type=application/json which fortunatly has been Asked and answered as well.
var url = "https://analyticsreporting.googleapis.com/v4/reports:batchGet?";
var data = {
"reportRequests":[{
"viewId":"12345678",
"dateRanges":[{ "startDate":"7daysAgo", "endDate":"today"}],
"metrics":[{"expression":"ga:users"}],
"dimensions": [{"name":"ga:pagePath"}]
}]
}
$.ajax({
url: url,
type: "POST",
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(results) {
console.log(results)
},
error: function(xhr, ajaxOptions, thrownError) {
alert('failed');
alert(xhr.status);
alert(thrownError);
}
});

Error while setting up Extjs Rest Proxy Create function

I am using Rest proxy in Extjs Model as:
Ext.define('ThemeApp.model.peopleModel', {
extend: 'Ext.data.Model', fields: [
{ name: 'userId' },
{ name: 'title' },
{ name: 'body'}
],
proxy: {
type: 'rest',
format: 'json',
limitParam:"",
filterParam: "",
startParam:'',
pageParam:'',
url:'http://jsonplaceholder.typicode.com/posts/1',
api: {
read : 'http://jsonplaceholder.typicode.com/posts/1',
create: 'http://httpbin.org/post'},
headers: {'Content-Type': "application/json" },
reader: {
type: 'json',
//rootProperty:'issues'
},
writer: {
type: 'json'
}
In my view I am calling create function as:
var user = Ext.create('posts', {"userId": 124,"title": "sunt","body": "quia"});
user.save();
As I am testing everything on http://jsonplaceholder.typicode.com/ so I am expecting that code will work cause when I test GET and POST functionality via Postman utility everything works fine.
Can anyone point out my error?
I found my mistake.
In the following code I was not setting the correct name of my model, as it won't be "Posts"
var user = Ext.create('posts', {"userId": 124,"title": "sunt","body": "quia"});
user.save();
Also if you are trying with http://jsonplaceholder.typicode.com/ you are not supposed to send ID in the post request.