I created a simple API with Hapi that has a route I can POST to, which looks like this:
server.route({
method: "POST",
path: "/hello",
handler: function(request, reply) {
// It doesn't ever get to here
return reply({hello: request.payload.name});
},
config: {
validate: {
payload: {
name: Joi.string().required()
}
}
}
});
I can successfully send a POST request to this path in Postman:
It returns the expected response. But, when I use this piece of Javascript to send the request:
fetch("http://localhost:1111/hello", {
mode: "cors"
body: {name: "John Doe"}
}).then(() => {
console.log("yay! it worked");
});
This fails, and says "value" must be an object.
It turns out, I just needed to stringify the JSON first, and then it worked:
fetch("http://localhost:1111/hello", {
mode: "cors"
body: JSON.stringify({name: "John Doe"})
}).then(() => {
console.log("yay! it worked");
});
Related
I've created a new Zapier integration and it works okay so far. But when I turn of the Zap created using the integration, the unsubscribe webhook doesn't get called. For testing, I've used https://webhook.site as the unsubscribe url but it never gets called. Here's the code that shows in the unsubscribe code mode:
const options = {
url: 'https://webhook.site/XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'X-KEY': bundle.authData.key
},
params: {
},
body: {
'hookUrl': bundle.subscribeData.id,
'key': bundle.authData.key
}
}
return z.request(options)
.then((response) => {
response.throwForStatus();
const results = response.json;
// You can do any parsing you need for results here before returning them
return results;
});
I am trying out to write the swagger using fastify and fastify-swagger in localhost. However my real server is running somewhere else which has the backend logic. I am trying to proxy my localhost API call to the remote upstream using fastify-http-proxy.
So in essence, the swagger I want to serve from localhost and and all the actual API call I want to proxy to remote upstream.
My fastify-http-proxy configuration:
fastify.register(require('fastify-http-proxy'), {
upstream: "https://mystaging.com/notifications",
prefix: '/notifications',
replyOptions: {
rewriteRequestHeaders: (originalRequest, headers) => {
return {
...headers,
};
},
},
async preHandler (request, reply) {
console.log('Request URL: ', request.url);
if (request?.url?.includes('api-docs')) {
console.log('Request contains api-docs. Ignore the request...');
return;
}
},
});
Basically my intention is that any upcoming request coming to http://127.0.0.1:8092/notifications should be proxied to and served by the https://mystaging.com/notifications. E.g. POST http://127.0.0.1:8092/notifications/agent-notifications should be actually forwarded to https://mystaging.com/notifications/agent-notification. That's why I configured the fastify-http-proxy as the above way.
My fastify-swagger configuration:
fastify.register(require('fastify-swagger'), swaggerConfig);
const swaggerConfig = {
openapi: {
info: {
title: `foo bar`,
description: `API forwarded for notifications service`,
version: '1.0.0'
},
servers: [
{ url: `${server}` },
],
tags: [
{ name: 'notifications', description: "Notifications"},
],
components: {
securitySchemes: {
authorization: {
type: 'http',
scheme: 'bearer',
bearerFormat: 'JWT',
description: 'JWT access token to authorize the request, sent on the request header.'
}
}
}
},
exposeRoute: true,
routePrefix: `localhost:8092/notifications/external/api-docs`,
};
Once I opened the swagger in the browser using URL http://localhost:8092/notifications/external/api-docs/static/index.html, I am seeing other than the notifications tag, there are very REST verb of /notifications/ is coming up as the attached picture.
Once I turn of the fastify-http-proxy, everything works fine.
What am I missing/messing up here.
Screenshot of spurious default routes:
Versions used:
"fastify": "^3.21.6",
"fastify-auth0-verify": "^0.5.2",
"fastify-swagger": "^4.8.4",
"fastify-cors": "^6.0.2",
"fastify-http-proxy": "^6.2.1",
Notes added further:
The route specification looks like:
module.exports = async function (fastify, opts) {
fastify.route({
method: 'POST',
url: `${url}/agent-notifications`,
schema: {
description: 'Something',
tags: ['notifications'],
params:{
$ref: 'agent-notifications-proxy-request#',
},
},
handler: async (request, reply) => {
}
});
}
And here is the agent-notifications-proxy-request:
module.exports = function (fastify) {
fastify.addSchema({
$id: 'agent-notifications-proxy-request',
title: "AgentNotificationRequest",
description:'Trying out',
type: 'object',
example: 'Just pass the same stuff as-is',
properties: {
'accountId': {
type: 'string'
},
'templateName': {
type: 'string'
},
"bodyParams": {
type: "object",
},
"includeAdmin": {
type: 'boolean'
},
"serviceName": {
type: 'string'
},
},
});
};
I'm trying to send e-mails with MS Graph 1.0 and I have not any get any result or response. E-Mails haven't been sent and sendMail method don't return any error o message... it only says "null".
My code is based on this example https://github.com/microsoftgraph/msgraph-sdk-javascript#post-and-patch and looks like this:
// Initialize Graph client
const client = graph.Client.init({
authProvider: (done) => {
done(null, accessToken);
}
});
try {
// construct the email object
var mail = {
subject: "Microsoft Graph JavaScript Sample",
toRecipients: [{
emailAddress: {
address: "mail#domain.com"
}
}],
body: {
content: "<h1>MicrosoftGraph JavaScript Sample</h1>Check out https://github.com/microsoftgraph/msgraph-sdk-javascript",
contentType: "html"
}
};
client
.api('/me/sendMail')
.post({message: mail}, (err, res) => {
console.log("---> " + res);
});
console.log("Try ends");
} catch (err) {
parms.message = 'Error retrieving messages';
parms.error = { status: `${err.code}: ${err.message}` };
parms.debug = JSON.stringify(err.body, null, 2);
res.render('error', parms);
}
I guess mail var needs a header, but anyway, API should return me something, right? And, obviously, which is the problem with the email sending?
I finally added rawResponse to .post call and look at err log...
client
.api('/me/sendMail')
.header("Content-type", "application/json")
.post({message: mail}, (err, res, rawResponse) => {
console.log(rawResponse);
console.log(err);
});
... and I could see that I had problem with my authentication token. So, I was using the api correctly and code from the question is ok.
I am trying to post some data usng this.$http.post and I could not figure out how to pass in the data through the route api..
new Vue({
el: '#root',
data: {
newName: '',
nameList: []
},
methods: {
addName(){
this.nameList = this.nameList.concat(this.newName);
var name = this.newName;
this.newName = '';
this.$http.post('/api/name', {name: name}).then((response) => {
console.log(response.message);
});
}
},
mounted(){
this.$http.get('/api/name').then((response) => {
this.nameList= this.nameList.concat(JSON.parse(response.body));
console.log(this.nameList);
});
}
});
It is not very clear, what is the exact issue, here, what exact API you are trying to hit.
If you are trying to hit: /api/name/:someName, you can do following
this.$http.post('/api/name/'+name ).then((response) => {
console.log(response.message);
});
If you are trying to hit: /api/:someName with payload, you can do following
this.$http.post('/api/' + name, {name: name}).then((response) => {
console.log(response.message);
});
Let me know if it helps.
I'm trying to send a POST request to the OneSignal REST API using fetch:
var obj = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
'app_id': '(API KEY)',
'contents': {"en": "English Message"},
'app_ids': ["APP IDS"],
'data': {'foo': 'bar'}
})
}
fetch('https://onesignal.com/api/v1/notifications', obj)
I know you're not really supposed to put your API key in client code, but this is just a test to see if it would work. Besides, the error I'm getting isn't a bad response from the server, it's:
Possible Unhandled Promise Rejection (id: 0):
unsupported BodyInit type
I've tried putting a catch method on the fetch, but it doesn't get called.
At a bit of a loss, not really sure how to proceed.
Thanks in advance!
Even I tried the same POST request for One-Signal REST API for creating notifications,the below worked for me fine.
const bodyObj = {
app_id: "**********",
included_segments: ["All"],
data: {"foo": "bar"},
contents: {"en": "Hi good morning"}
}
fetch('https://onesignal.com/api/v1/notifications',{
method:'POST',
headers:{
'Authorization':'Basic **********',
'Content-Type':'application/json'
},
body:JSON.stringify(bodyObj)
})
.then((response) => response.json())
.then((responseJson) => {
console.log("success api call");
})
.catch((error) => {
console.error(error);
});
Have you tried to change your json to the one below?
JSON.stringify({
app_id: '(API KEY)',
contents: {en: "English Message"},
app_ids: ["APP IDS"],
data: {foo: 'bar'}
})
Or even tried a simpler json?