Calling POST method in serverless offline using Postman - aws-lambda

I'm running serverless offline in node.js. When I try hitting the POST endpoint on Postman the request goes on forever and does not seem to call my handler. I'm not sending anything in the request body. It did not make a difference.
Below are examples of the code I'm running
handlers.js file
module.exports.postHandler = async (event, context, callback) => {
console.log("Inside POST Method");
}
Inside serverless.yml
postHandler:
handler: src/handlers.postHandler
events:
- http:
method: post
path: v1/post/handler
I have a GET method setup very similarly. That looks to be working fine
Edit:
I tried sending an empty request on an invalid POST route. Postman still keeps sending the request endless. When I try the same with GET I get the error - Serverless-offline: route not found. Not sure why POST requests do not resolve.

You need to respond to the client in your post request handler, you dont. Return 200 and give an empty json response it will work
Also make sure you are posting to the API POST Route, and giving it data it needs. i.e)
example:
// dont forget content type and content length headers
POST(host, path, { body: { ...data } })
example get:
GET(host, path, "?query=params")
Your current handler
module.exports.postHandler = async (event, context, callback) => {
console.log("Inside POST Method");
}
do,
module.exports.postHandler = async (event, context, callback) => {
context.status = 200;
context.message = "Youre welcome"
}

Related

Cypress intercept does not match route with status 204

I am implementing cypress tests in our Angular application and have a problem waiting for a request to finish. I am guessing it has to do with the status of the Request being 204 instead of 200.
This is the function/command I am calling in my test:
export function logout() {
cy.intercept('/api/security/logout').as('logoutRequest');
cy.getCookie('SESSION').then((cookie) => {
if (cookie != null) {
cy.request(
{
method: 'POST',
url: '/api/security/logout',
}
);
}
});
cy.wait('#logoutRequest');
}
My problem is, that the route /api/security/logout is not recognized as alias #logoutRequest and therefore the wait always timeouts. Even though there is a vaild request. As you can see here in the test protocol:
I have tried modifing the route with * or ** but without success. I would be very glad if you could help me out.
You can't use cy.intercept() to catch cy.request().
cy.intercept(), cy.server(), and cy.route()
cy.request() sends requests to actual endpoints, bypassing those defined using cy.route() or cy.intercept()
Just chain .then() off the request to handle the reply
cy.request({method: 'POST', url: '/api/security/logout', failOnStatusCode: false})
.then(response => {
expect(response.status).to.eq(200)
})

Send POST request to Laravel web.php route

I have a simple Vue app in which I am sending POST request with options (table filtering variables) to the back-end. I want to be able to destructure the object and debug it in my TestController in Laravel 8, so I want to send the options to web.php via URL, not to api.php. Since options is an object, I cannot just drop it in the URL.
Ultimately I want to be able to preview my Laravel respond in browser, so I know it returns correct data from server.
So how can I achieve this?
in Vue FormComponent <form #submit="formSubmit"> and script
function formSubmit(e) {
e.preventDefault();
let currentObj = this;
axios.post('/formSubmit', {
name: this.name,
description: this.description
}).then(function(response) {
currentObj.output = response.data;
console.log(currentObj);
}).catch(function(error) {
currentObj.output = error;
});
}
Firstable, create POST route for your request. Then just make POST request to this route url and put your POST params (your object) to request body. You can use Axios as example
let filterOptions = {...};
axios.post(url, filterOptions).then().catch();
UPD And response for your request you can see in browser developer console on network tab

GET request with query parameters returns 403 error (signature does not match) - AWS Amplify

Problem
I was trying to use 'aws-amplify' GET API request with query parameters on the client side, but it turned out to be Request failed with status code 403, and the response showed:
"message":"The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.
Note: React.js as front-end, Javascript as back-end.
My code
Front-end
function getData() {
const apiName = 'MyApiName';
const path = '/path';
const content = {
body:{
data:'myData',
},
};
return API.get(apiName, path, content);
}
Back-end
try {
const result = await dynamoDbLib.call("query", params);
} catch (e) {
return failure({ status: false });
}
What I did to debug
The GET lambda function works fine in Amazon Console (Tested)
If I change the backend lambda function so that the frontend request can be made without parameters, i.e. return API.get(apiName, path), then no error shows up.
My question
How can I make this GET request with query parameters works?
I changed GET to POST (return API.post()), everything works fine now.
If anyone can provide a more detailed explanation, it would be very helpful.

Sails - Access Controller function(req,res) from Service

I have a Controller method: DbController.create to create database entries. This is the following format:
create: function (req, res) {
var params = req.body;
Db.create({
...
There is a route for this Controller method:
'POST /createData': 'DbController.create'
I can use CURL to this URL with no problems (curl -X POST --data 'userId="testuser1"' http://localhost:1337/createData), and from my UI code I can call this using sails-io.js and io.socket.post(....).
The problem is that I want to use this from my Service now (DbService). I'm not sure how I can go about this, because simply using DbController.create requires a req and res parameter to be passed, but all I have is the data/params/body.
Thanks
The best way would be to move the create logic in some service method so that it can be used from anywhere in project. Once this is done, then invoke that method with necessary parameters from DbController.create as well as from some other service.
Sample:
// DBService:
createData: (params, callback) => {
Db.create(params)...
}
// DBController:
create: (req, res) => {
const params = req.body;
DBService.createData(params, (err, results) => {
if (err) {
return res.serverError(err);
}
return res.json(results);
});
}
// SomeOtherService:
someMethod: (params, callback) => {
DBService.createData(params, callback);
}
Another way (which will unnecessary make http request) is to make a HTTP call from service to the API endpoint of DbController.create from the service.

Making a POST request using Superagent, AWS Lambda, API Gateway

I am using AWS Lambda and API Gateway to create a custom endpoint for load tests. I have uploaded my handler function which is in a file, along with the node modules needed for the function in a zip, and set up the API Gateway API correctly according the instructions (in line with the way that I had made it work before), but I keep getting the error: {"error": "Missing Authentication Token"}. Everything I have seen online thus far points to the idea that the url that I am passing in with the POST request is invalid, but I have made a similar endpoint work with a GET request. As far as I know I have set up the POST request (using Superagent) correctly, and am passing in a valid access-token, as well as hardcoded params as part of the URL (valid params).
// Dependencies
var request = require('superagent');
var sync = require('synchronize');
exports.handler = function(event, context) {
sync.fiber(function() {
// Grabs params passed into the URL as a JSON object
var querystring = (event.querystring);
// Replaces params with an updated version which includes a single quotation
var queryStringUpdate = querystring.replace(/=/g, ":").replace(/}/g, "'}").replace(/:/g, ":'").replace(/,/g, "',");
// Updates the param information and sets it as a new string
eval('var queryString2 =' + queryStringUpdate);
// Define specific query params to be used in the REST calls
var userId = (queryString2.userId === undefined ? '229969' : queryString2.userId);
var roomdId = (queryString2.roomId === undefined ? '4' : queryString2.roomId);
var inviterId = (queryString2.inviterId === undefined ? '212733' : queryString2.inviterId);
var createInvitePost = function() {
request
.post('https://some_url/v2/invites/212733/create')
.set({'access-token': 'some_access_token'})
.set('Content-Type', 'application/json')
.query({user_id: "229969"})
.query({room_jid: "4"})
.end(function(err, res){
if (err) {
context.fail("Uh oh, something went wrong");
} else {
context.done(null, "Hurray, it worked!!");
}
});
};
try {
createInvitePost();
} catch(errOne) {
alert("No bueno!!");
}
});
};
Any thoughts on this?? Thanks
I usually get this error when I've missed some part of the URL needed for my API. In the past it's either been the name of the stage, misspelled resource name, or a missing Path parameter.
I'm from the Api Gateway team.
As others have said, the most common cause of the 403 response you're getting is an incorrect path/method. I'm not familiar with Superagent, but if you've run the same request in Postman and cURL then I would be surprised if you had the wrong path/method.
Maybe also check on a wire log if possible, to make sure that your querystring logic isn't appending a forward slash prior to the '?'.
Some things to check:
Have you deployed any recent changes to your API?
Is the stage 'v2' (I'm assuming that's the stage) pointing at a deployed version of the API that has the POST to invites/212733/create?
The 'access-token' should have no effect on the Api Gateway layer. If you're trying to use a native Api Gateway Api Key, the header is 'x-api-key'.
Jack

Resources