My POST request works on Postman but not with axios - axios

I have a nuxt project deployed on Netlify and now I want to add a newsletter (add a subscriber to my audience on Mailchimp). To achieve that, I've opted to use the AWS serverless lambda functions. To be honest, it's the first time that i've heard about serverless functions. I found this tutorial https://hashinteractive.com/blog/nuxt-js-mailchimp-integration-add-contact-to-list/ and at the end, i've decided to make a test on Postman. I've made a post to http://localhost:8888/.netlify/functions/subscribe and it worked. But when I try the same thing with axios I get the error 405 (method not allowed).
Newsletter.vue
<form #submit.prevent='submitNewsletter' class="newsletter__form" >
<input type="email" placeholder="E-mail" class="newsletter__form-input" v-model="email">
<button class="newsletter__form-button" type="submit">Subscribe</button>
</form>
</div>
</template>
<script>
import axios from 'axios';
export default {
data(){
return{
email: ''
}
},
methods:{
submitNewsletter(){
axios.post('http://localhost:8888/.netlify/functions/subscribe', { email: this.email}, {
headers: {
methods: 'POST',
'Content-Type':'application/json'
}
})
.then(function (response) {
console.log(response);
}).
catch((error) =>{
console.log('The error:' + error)
})
this.$toasted.success("Thank you for your subscription !!!", {
theme: "toasted-primary",
position: "top-left",
containerClass: 'myContainer',
fitToScreen: true,
fullWidth: true,
duration : 5000
});
}
}
}
</script>
functions > subscribe > subscribe.js
const fetch = require('node-fetch');
const base64 = require('base-64');
exports.handler = async (event, context) => {
// Only allow POST
if (event.httpMethod !== 'POST') {
return { statusCode: 405, body: 'Method Not Allowed' };
}
const errorGen = msg => {
return { statusCode: 500, body: msg };
};
try {
const { email } = JSON.parse(event.body);
console.log(email);
if (!email) {
return errorGen('Missing Email');
}
const subscriber = {
email_address: email,
status: 'subscribed',
};
console.log(subscriber);
console.log(JSON.stringify(subscriber));
const creds = `blooming-thoughts:${process.env.MAILCHIMPS_API_KEY}`;
const response = await fetch(`https://us20.api.mailchimp.com/3.0/lists/${process.env.AUDIENCE_ID}/members/`, {
method: 'POST',
headers: {
Accept: '*/*',
'Content-Type': 'application/json',
Authorization: `Basic ${base64.encode(creds)}`, },
body: JSON.stringify(subscriber),
});
const data = await response.json();
if (!response.ok) {
// NOT res.status >= 200 && res.status < 300
return { statusCode: data.status, body: data.detail };
}
return {
statusCode: 200,
body: JSON.stringify({ msg: "You've signed up to the mailing list!", detail: data, }),
};
} catch (err) {
console.log(err); // output to netlify function log
return {
statusCode: 500,
body: JSON.stringify({ msg: err.message }),
};
}
};
My netlify.toml
[build]
publish = "dist"
functions = 'functions'
I've made a push to my repository and netlify built without any error, but when I try to add a newsletter from my site nothing happens.

I've solved my problem. If you're having trouble like I was, follow these steps:
Create a folder called functions in your root directory, then create a index.js (the file name is up to you).
Create a file called netlify.toml and add the following code :
[build]
functions = "functions"
Then, inside your index.js goes the code that will communicate with your API
On the vue component, make a post request to the <your-site>/.netlify/functions/index . You can find the endpoint going to functions on netlify dashbord.
Don't forget to register your env variables on Netlify (Build & Deploy) and that's it.

Related

Cookie does not appear to be sent via fetch or hapi server is unable to receive cookie

So I have a simple backend server created with Hapi API and the frontend I'm using fetch. These are on different ports so I have CORs enabled and all the sweet stuff. I'm currently trying to set a refresh token in the browser using a http only cookie. As far as I can verify, the http only cookie is being set in the browser when login function is completed. I'm currently trying to send the http only cookie back to the server so I can set up the refresh token route and I can't seem to send or even verify that http token is sent back to the server.
Here's the server setting.
"use strict";
require("dotenv").config();
const Hapi = require("#hapi/hapi");
const Jwt = require("#hapi/jwt");
const routes = require("./routes/routes");
exports.init = async () => {
const server = Hapi.server({
port: 3000,
host: "localhost",
routes: {
cors: {
origin: ["*"],
credentials: true,
},
},
});
require("./models");
await server.register(Jwt);
server.auth.strategy("jwt", "jwt", {
keys: { key: process.env.SECRET_KEY, algorithms: ["HS256"] },
verify: { aud: false, iss: false, sub: false, exp: true },
validate: false,
});
server.state("refresh", {
ttl: 1000 * 60 * 60 * 24,
isSecure: true,
isHttpOnly: true,
encoding: "base64json",
clearInvalid: true,
strictHeader: true,
isSameSite: "None",
});
server.route(routes);
return server;
};
process.on("unhandledRejection", (err) => {
console.log(err);
process.exit(1);
});
Here's the login request and returns the http only cookie. This part works, the http cookie is returned and set.
const validateUserAndReturnToken = async (req, h) => {
const user = await User.findOne({
$or: [{ email: req.payload.username }, { username: req.payload.username }],
});
if (user) {
const match = await bcrypt.compare(req.payload.password, user.passwordHash);
if (match) {
const token = await createToken(match);
const refreshToken = await createRefreshToken(match);
h.state("refresh", refreshToken);
return { id_token: token, user: formatUser(user) };
} else {
throw boom.notAcceptable("Username and password did not match.");
}
} else {
throw boom.notAcceptable("Username or email was not found.");
}
};
Here's the fetch request I'm using to test sending a http cookie only back. I have credential: include so I don't know what is problem?
import type { DateInfo } from "#/stores/application";
const api = "http://localhost:3000/report";
let token = localStorage.getItem("user-token");
const headers = new Headers();
headers.append("Authorization", `Bearer ${token}`);
headers.append("Content-Type", "application/json");
export const getJobReport = async (dateFilter: DateInfo) => {
let response = await fetch(
`${api}/${dateFilter.startDate}/${dateFilter.endDate}`,
{
method: "GET",
headers,
credentials: "include",
}
);
return await response.json();
};
I have checked the application tab as well as the network request so I know set cookie is being sent and set on the browser. The problem is I can't seem to get the cookie back from the browser when fetch request is sent back to the server.
Here's the code I'm using to just check the existence of the cookie. According to Hapi Doc , req.state[cookie-name] which in this case is 'refresh' should have the cookie value. Refresh is returning undefined so I went up one level and check for req.state and gets an empty object {}.
route
{
method: "GET",
path: "/report/{startDate}/{endDate}",
options: {
auth: "jwt",
state: {
parse: true,
failAction: "error",
},
validate: {
params: Joi.object({
startDate: Joi.string(),
endDate: Joi.string(),
}),
},
},
handler: handlers.report.getJobApplicationReport,
},
handler
const getJobApplicationReport = async (req, h) => {
console.log("TEST", req.state);
const start = new Date(req.params.startDate);
const end = new Date(req.params.endDate);
try {
const applications = await Application.find({
dateApplied: { $gte: start, $lt: end },
});
// 'Applied', 'In Process', 'Rejected', 'Received Offer'
const total = applications.length;
let rejectedCount = 0;
let inProcessCount = 0;
applications.forEach((app) => {
if (app.status === "Rejected") {
rejectedCount++;
}
if (app.status === "In Process") {
inProcessCount++;
}
});
return {
total,
rejectedCount,
inProcessCount,
};
} catch (error) {
console.log(error);
throw boom.badRequest(error);
}
};
I've looked through all the Hapi documentation, fetch documentation and stackoverflow question/answers but can't seem to find a solution. I can't verify whether it's the fetch request that's not sending the http only cookie or the server setting that's not parsing it. Any help to determine the issue or solution would be greatly appreciated.
I've looked through all the Hapi documentation, fetch documentation and stackoverflow question/answers but can't seem to find a solution. I can't verify whether it's the fetch request that's not sending the http only cookie or the server setting that's not parsing it. Any help to determine the issue or solution would be greatly appreciated.

Unable to receive mail sent via sendgrid

I'm creating a contact form using Nextjs and SendGrid, according to this header status
202
{
server: 'nginx',
date: 'Thu, 08 Dec 2022 16:29:25 GMT',
'content-length': '0',
connection: 'close',
'x-message-id': 'CaVdpVAURza6JrUF7yIQQA',
'access-control-allow-origin': 'https://sendgrid.api-docs.io',
'access-control-allow-methods': 'POST',
'access-control-allow-headers': 'Authorization, Content-Type, On-behalf-
of, x-sg-elas-acl',
'access-control-max-age': '600',
'x-no-cors-reason':
'https://sendgrid.com/docs/Classroom/Basics/API/cors.html',
'strict-transport-security': 'max-age=600; includeSubDomains'
}
the email is sent but I find nothing in my inbox,
and this error occurs in the terminal
API resolved without sending a response for /api/contact, this may result in stalled requests.
I don't know what mistake I've done but. I invite you to look at my code bellow:
API :
import sgMail from "#sendgrid/mail";
export default function handler(req, res) {
if (req.method !== "POST") {
res.status(405).json({ message: "INVALID_METHOD" });
return;
}
// Variables from the client side
var name = req.body.name;
var email= req.body.email;
var subject= req.body.subject;
var content = req.body.content;
// auto line break message
const message = content
.replace(/\n/g, "<br>")
.replace(/\r/g, "<br>")
.replace(/\t/g, "<br>")
.replace(/<(?!br\s*\/?)[^>]+>/g, "");
// giving the api key API
sgMail.setApiKey(process.env.KEY_SENDGRID);
// Creating message
const sendGridMail = {
to: "arotiana4612#gmail.com",
from: "kaspersky2mahanaima#gmail.com",
subject: subject,
templateId: "d-b48909edf062437e8442f861a4c8be29",
dynamic_template_data: {
name: name,
email: email,
subject: subject,
content: message,
},
};
// SENDING MESSAGE VIA SENDGRID
(async () => {
try {
await sgMail.send(sendGridMail)
.then((response) => {
console.log(response[0].statusCode)
console.log(response[0].headers)
})
.catch((error) => {
console.error(error)
})
} catch (err){
console.error(err);
res.status(500).json({
error:JSON.stringify(err),
message: "ERROR_WITH_SENDGRID",
});
}
})();
}
And this is the method from the client side that from which I get the data:
const onSubmit: SubmitHandler<Inputs> = async (formData) => {
if (!isLoading) {
setIsLoading(true);
const response = await fetch("/api/contact", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(formData),
});
const result = await response.json();
setIsLoading(false);
if (!response.ok) {
console.log("error sending email:",result);
} else {
console.log("ok");
}
return result;
}
};
I want to receive the mail in my inbox. Your help would be very appreciated, I'm strugling

How to do a rest post request using apollo client?

I know that we can also perform rest request using apollo, but I cant figure out how to do a post request, Can someone help me with it?
My REST post request endpoint is: <url>/transaction/getbyhash
Payload:
{"hash":"4e23f9e1d1729996de46fc94d28475b4614f101d72a98f221493f900dc33e0c2"}
Can someone please help me write the same request using apollo client and graphql-tag ?
You can use apollo-link-rest to call REST API inside your GraphQL queries.
E.g.
rest-api-server.ts:
import express from 'express';
import faker from 'faker';
const app = express();
const port = 3000;
app.use(express.json());
app.post('/api/transaction/getbyhash', (req, res) => {
console.log(req.body);
res.json({
email: faker.internet.email(),
name: faker.name.findName(),
});
});
app.listen(port, () => console.log(`HTTP server is listening on http://localhost:${port}`));
client.ts:
import { ApolloClient } from 'apollo-client';
import { RestLink } from 'apollo-link-rest';
import { InMemoryCache } from 'apollo-cache-inmemory';
import gql from 'graphql-tag';
import fetch from 'isomorphic-fetch';
const restLink = new RestLink({
uri: 'http://localhost:3000/api/',
customFetch: fetch,
headers: {
'Content-Type': 'application/json',
},
});
const client = new ApolloClient({
cache: new InMemoryCache(),
link: restLink,
});
const getbyhashQuery = gql`
fragment Payload on REST {
hash: String
}
query Me($input: Payload!) {
person(input: $input) #rest(type: "Person", method: "POST", path: "transaction/getbyhash") {
email
name
}
}
`;
const payload = { hash: '4e23f9e1d1729996de46fc94d28475b4614f101d72a98f221493f900dc33e0c2' };
client.query({ query: getbyhashQuery, variables: { input: payload } }).then((res) => {
console.log(res.data);
});
The logs:
{
person: {
email: 'Bryce34#gmail.com',
name: 'Miss Jaren Senger',
__typename: 'Person'
}
}
package versions:
"apollo-cache-inmemory": "^1.6.6",
"apollo-client": "^2.6.10",
"apollo-link": "^1.2.14",
"apollo-link-rest": "^0.7.3",
"graphql-anywhere": "^4.2.7",
"graphql": "^14.6.0",
"isomorphic-fetch": "^3.0.0",

Sharepoint list item using Api Rest

I need to get a list's items, so I created this function
export function retrieveSPItems(spToken, alias) {
var url = `{path_to_my_site}/_api/web/Lists/getByTitle('Briefs')/ItemCount`;
var myHeaders = new Headers({
Accept: "application/json;odata=nometadata",
Authorization: spToken,
});
return fetch(url, {
method: "get",
headers: myHeaders,
}).then((response) => response.json());
}
As a output I get 3000.
when I change the url to
var url = `{path_to_my_site}/_api/web/Lists/getByTitle('Briefs')/Items`;
I get an empty list!
PS :
It's work in Postman with no problem
The token is generated by adaljs :
Get Token
authContext.acquireToken(SP_BASE_URL, function (error, token){....})
Adal config
export const adalConfig = {
tenant: CURRENT_TENANT,
clientId: CURRENT_APP_ID,
endpoints: {
api: CURRENT_APP_ID,
graph: GRAPH_BASE_URL,
sharepoint: SP_BASE_URL,
},
cacheLocation: "localStorage",
validateAuthority: true,
};
So I need to know :
what the reason fot this issue?
How can I fix it?
It's too general information, you need debug and figure out the detailed error information.
My test demo:
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="Scripts/adal.js"></script>
<script type="text/javascript">
var authContext = null;
var user = null;
(function () {
window.config = {
instance: 'https://login.microsoftonline.com/',
tenant: 'xxx.onmicrosoft.com',
clientId: '9afc37cb-x-x-x-xxx',
postLogoutRedirectUri: window.location.origin,
endpoints: {
graphApiUri: "https://graph.microsoft.com",
sharePointUri: "https://xxx.sharepoint.com/",
},
cacheLocation: 'localStorage' // enable this for IE, as sessionStorage does not work for localhost.
};
authContext = new AuthenticationContext(config);
var isCallback = authContext.isCallback(window.location.hash);
authContext.handleWindowCallback();
//$errorMessage.html(authContext.getLoginError());
if (isCallback && !authContext.getLoginError()) {
window.location = authContext._getItem(authContext.CONSTANTS.STORAGE.LOGIN_REQUEST);
}
user = authContext.getCachedUser();
if (!user) {
authContext.login();
}
//authContext.acquireToken(window.config.clientId, function (error, token) {
// console.log('---');
//})
authContext.acquireToken(window.config.endpoints.sharePointUri, function (error, token) {
alert(token);
if (error || !token) {
console.log("ADAL error occurred: " + error);
return;
}
else {
var listUri = window.config.endpoints.sharePointUri + "sites/lee/_api/web/lists/GetByTitle('mylist')/items?$select=Title";
$.ajax({
type: "GET",
url: listUri,
headers: {
"Authorization": "Bearer " + token,
"accept": "application/json;odata=verbose"
}
}).done(function (response) {
console.log("Successfully fetched list from SharePoint.");
var items = response.d.results;
for (var i = 0; i < items.length; i++) {
console.log(items[i].Title);
$("#SharePoint").append("<li>" + items[i].Title + "</li>");
}
}).fail(function () {
console.log("Fetching list from SharePoint failed.");
})
}
})
}());
</script>

How to configure API URL running on localhost on port 8080 in nuxt js?

I have the following vue file. My REST API base URL is http://localhost:8080/api/. When I access http://localhost:8080/api/dfc/system/docbases directly, I get the response as shown.
["gr_swy","SubWayX_DEMO"]
But I want to get the response through nuxt js which is running on http://localhost:3000/restapi/. I tried to follow all the articles, but not able to figure out where I'm doing wrong.
<template>
<div class="container">
{{docbases}}
</div>
</template>
<script>
import axios from "axios";
#import axios from "../../.nuxt/axios"; (tried both)
export default {
methods: {
// asyncData({ req, params }) {
// return axios.get("http://localhost:8080/api/dfc/system/docbases")
// .then(res => {
// return { docbases: res.data };
// }).catch((e) => {
// error({ statusCode: 404, message: 'Not found' })
// })
// },
async asyncData ({ params }) {
const { data } = await axios.get('http://localhost:8080/api/dfc/system/docbases');
return { docbases: data }
}
},
head: {
title: "D2Rest"
}
};
</script>
My nuxt.config.js is like this: I tried changeOrigin with true and false both. Can you please help me what extra things I need to configure?
axios: {
proxy: true,
},
env: {
baseUrl: process.env.BASE_URL || 'http://localhost:3000'
},
proxy: {
'/api/': {
target: 'http://localhost:8080/',
pathRewrite: { "^/api": "" },
changeOrigin: false,
prependPath: false
}
},
Based on your configuration, I'm assuming you're using the Nuxt Axios module...
The problem seems to be that you're importing Axios unnecessarily, thus bypassing your axios configuration in nuxt.config.js. The Nuxt Axios module docs describe its usage in components:
export default {
async asyncData({ $axios }) {
const ip = await $axios.$get('http://icanhazip.com')
return { ip }
}
}
Note the destructured parameter $axios. Use that parameter instead of importing your own instance of axios (i.e., don't do import axios from 'axios'), which is not the same as the one configured by Nuxt. No other imports are needed for $axios.
Proxy URL
Another problem is that your explicitly requesting the proxy address in the URL, but that should be excluded:
// const { data } = await $axios.get('http://localhost:8080/api/dfc/system/docbases'); // DON'T DO THIS
const { data } = await $axios.get('/api/dfc/system/docbases');
Sorry, I didn't enable Cross Origin in my java code. I have enabled now and it's resolved.
#CrossOrigin(origins = "http://localhost:3000")