Getting request body as a string from API gateway, expecting JSON content - javascript

I have recently started to create a slack slash command bot for learning purpose. I am getting the different format of request body from API gateway and nodejs app on EC2 server. I just want to get JSON format of request body from API gateway. How can get it?
Let's have a look at both the body format and serverless.yml file.
First, I have installed the serverless framework & created the serverless.yml file with the following code,
service: as-serverless-slack-bot
# NOTE: update this with your service name
# You can pin your service to only deploy with a specific Serverless version
# Check out our docs for more details
# frameworkVersion: "=X.X.X"
provider:
name: aws
runtime: nodejs8.10
functions:
info:
handler: handler.info
events:
- http:
method: post
path: slack/info
cors: true
Now, I have deployed it successfully. However, when I execute slack slash command, I receive request body in string format from API gateway,
body: 'token=XXXXXX&team_id=XXXXXXXX&team_domain=XXXXXXX&channel_id=XXXXXXX&channel_name=XXXXXX&user_id=XXXXXX&user_name=XXXXXXX&command=%2Finfo&text=about+users&response_url=https%3A%2F%2Fhooks.slack.com%2Fcommands%2XXXXXXX%2XXXXXXXXXXX&trigger_id=562173962614.55XXXXXXXXX.326e28e8599XXXcacf0XXXXXa'
While, for the same action, I am getting JSON formatted request body in EC2 nodejs app.
{
"body": {
"token": "xxxxxxxxx",
"team_id": "xxxxxx",
"team_domain": "xxxxxx",
"channel_id": "xxxx",
"channel_name": "xxxx",
"user_id": "xxx",
"user_name": "xx",
"command": "/info",
"text": "about users",
"response_url": "https://hooks.slack.com/commands/x/x/x",
"trigger_id": "560161450593.558xxxxxxxx3.3741c456xxxxx05cc6xxx62"
}
}
So, how can I get request body in JSON format from API gateway?

This is correct. Default lambda integration is via "lambda proxy" which bypasses API Gateway's request/response transformers. You basically get the raw payload to deal with.
If you want API Gateway to do some of the work, you need to switch integration to lambda and configure API Gateway to accept application/json as a request type.
https://serverless.com/framework/docs/providers/aws/events/apigateway#lambda-integration

Related

Electron builder - publish to local artifactory, and add requestheaders for authentication

I'm trying to understand the Docs regarding custom publishing in electron builder, i have a local artifactory server with authentication,
so what i understand so far that when using this option it will automatically upload the newly created artifact to the URL pointed
assuming using release, but i also need to be an authentic user in order to upload, i tried adding requestheaders for authentication but i get the following error
package.json
`
"publish": {
"provider": "generic",
"url": "example.com/aa/bb",
"requestHeaders":{ "Authorization:":"Basic KEY" }
}
`
as soon as i try to do this i get this error
configuration.publish.requestHeaders has an unknown property 'Authorization'. These properties are valid: object {}
Any help appreciated
Seems to be the same as this issue in Electron-Builder.
As a workaround, you can try to set the basic credentials in the URL itself:
"publish": {
"provider": "generic",
"url": "myuser:mypass#example.com/aa/bb"
}
(see RFC-1738)

ServerRuntimeConfig is empty

I am working on my nextjs project under docker, and when using getStaticProps my backend api is not available(which is also under docker). So I connected frontend to backend via networks and if i hardcode api for ssr request it works. But when i try to utilize serverRuntimeConfig and publicRuntimeConfig so i could switch between them depending on where code is being ran I get {} for serverRuntimeConfig. However publicRuntimeConfig is fine and i can access api from it.
My next.config.js is:
module.exports = {
publicRuntimeConfig: {
// Will be available on both server and client
baseUrl: 'http://localhost/api/v1',
},
serverRuntimeConfig: {
// Will only be available on the server side
baseUrl: 'http://backend_nginx_1/api/v1/',
},
am I missing something ?
This will sound dumb, but I spent 2 hours seeing the empty file been recognized by the system and just seeing {}.
Now... restarting the server, gives you access to the content of the file.
That was my solution.
And it was not included in the documentation.
https://nextjs.org/docs/api-reference/next.config.js/runtime-configuration

Plaid web hook not firing

I'm trying to integrate Plaid transaction webhooks into an api, and seem to have trouble getting any webhooks to fire. I used the plaid quickstart code and added the webhook parameter:
Plaid.create({
apiVersion: "v2",
clientName: "Plaid Walkthrough Demo",
env: "<%= PLAID_ENV %>",
product: ["transactions", "auth"],
webhook: "http://localhost:3000/api/plaid/webhook",
key: "<%= PLAID_PUBLIC_KEY %>",//...
On the receiving end I'm just logging the req.body to see if webhook fired:
app.post("/api/plaid/webhook", (req, res) => {
console.log("WEBHOOK FIRED");
console.log(JSON.stringify(req.body));
});
When I tested the route in Postman, the req.body was logged as expected, but when creating a new PLAID Item it's not working. I'm currently working in Sandbox mode
Wrote to Plaid support and the reason it didn't work is because localhost:3000 is not a valid URL. Once i tried it on an actual server it worked.
As you already found out yourself, localhost:3000 won't work since it's not public (visible to Plaid).
When I want to test webhooks locally, I typically user services like:
https://postb.in
https://webhook.site
Like Plaid support mentioned, localhost:8000 isn't a public URL so Plaid can't see it.
However, its easy to give localhost a public URL using expose.sh. Then you can test the webhook locally.
Install expose.sh
For Mac or Linux, go to Expose.sh and copy/paste the installation code shown into a terminal.
For Windows go to Expose.sh, download the binary and put it somewhere in your PATH.
Expose your api to the web
Start your API server. Then run expose <port> where port is the port your API server is running on, like 80 or 8080.
Expose.sh will generate a random public expose.sh URL. You'll see output like
https://s3rh.expose.sh is forwarding to localhost:80
http://s3rh.expose.sh is forwarding to localhost:80
Then you can get Plaid to use the public HTTPS URL, which will forward to localhost.
I've written a full guide here
Disclaimer: I built expose.sh

Ionic v2 + CORS Preflight Access-Control-Allow-Methods

Having issues communicating with an external API via ionic serve and ionic run -l, essentially anything that uses a localserver.
I've followed the guide # http://blog.ionic.io/handling-cors-issues-in-ionic/, which provides an option for handling the issue in Ionic 1 projects, but I'm struggling to get it working in a v2 project.
Fetch API cannot load https://test.api.promisepay.com/items/100fd4a0-0538-11e6-b512-3e1d05defe79/make_payment. Method PATCH is not allowed by Access-Control-Allow-Methods in preflight response.
I have no control over how the API handles theses requests, as it is controlled by PromisePay.
Following the closest thing to a possible solution on StackOverflow: CORS with Firebase+IONIC2+Angularjs: No 'Access-Control-Allow-Origin' still exists
I've updated my ionic.config.json to
{
"name": "project",
"app_id": "xxxxxxx",
"proxies": [{
"path": "/api",
"proxyUrl": "https://test.api.promisepay.com"
}]
}
In the library that makes the http calls, I've updated the base URL to const PRE_LIVE_API = '/api';
The request method looks as follows:
let Requester = class Requester {
constructor() {
let config = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
this.config = config;
const baseUrl = PRE_LIVE_API;
this.log(`API endpoint: ${ baseUrl }`);
this.client = _requestPromise2.default.defaults({
baseUrl: baseUrl,
auth: {
user: config.userName,
pass: config.token
},
headers: {
Accept: 'application/json',
Authorization: `basic ${ config.apiToken }`
},
resolveWithFullResponse: true
});
}
When making a call to the most basic of API endpoints /status/ I am now receiving the following error:
"Error: Invalid URI "/api/status""
It seems the proxy path isn't being passed through.
I was facing the same problem when I was trying to use the MailGun to send e-mails using REST API.
The solution is to use HTTP instead of http. ionic 2 provides the class [HTTP]: http://ionicframework.com/docs/v2/native/http/ .
In your projects root folder, run this command from the terminal:
ionic plugin add cordova-plugin-http
In your .ts file:
import { HTTP } from 'ionic-native';
Then, wherever you want to send the HTTP post/get using Basic Authentication, use this:
HTTP.useBasicAuth(username, password)
//replace username and password with your basic auth credentials
Finally, send the HTTP post using this method:
HTTP.post(url, parameters, headers)
Hope this helps! Good luck!
For Development purposes where the calling url is http://localhost, the browsers disallow cross-origin requests, but when you build the app and run it in mobile, it will start working.
For the sake of development,
1. Install CORS plugin/Extension in chrome browser which will help get over the CORS issue.
2. If the provider is giving a JSONP interface instead of a normal get/post, You will be able to get over the CORS issue.
I prefer using the 1st option as not a lot of api's provide a jsonP interface.
For Deployment,
You need not worry as building a app & running it in your mobile, you will not face the same issue.
Solved. Explicitly setting the BaseURL constant (PRE_LIVE_BASE) to http://localhost:8100/api resolves the issue. Now all requests are passed via the proxy alias and subvert the CORS issue.
The only downside of this approach, is that I had to change a variable that was part of a package in node_modules, which will be overwritten during any future updates. So I should probably create my own fork for a cleaner solution.

how to test server REST API with testem

Testem has a config option serve_files that serves the client side code for me. But i need to run my server because It has a REST API, and client side uses it.
How do i configure testem to run my server before running the tests? Or is this against the testem rules?
Because testem runs on another port and my rest api references to rest api won't work.
So i need to tell testem to bypass serve_files and launch my actual server and test the files from there.
PS: Or another alternative would be to stub the api with sinonjs or something, would that be a proper approach? Then i wouldn't really be testing my API with the ember generated templates using the API.
You can use the API Proxy setting:
The proxy option allows you to transparently forward http requests to an external endpoint.
Simply add a proxies section to the testem.json configuration file.
{
"proxies": {
"/api": {
"port": 4200,
"host": "localhost"
},
"/xmlapi": {
"port": 8000,
"host": "localhost"
}
}
}
This functionality is implemented as a transparent proxy hence a request to http://localhost:7357/api/posts.json will be proxied to http://localhost:4200/api/posts.json without removing the /api prefix.

Categories

Resources