I am trying to take user emails and put them into sendgrid as a contract list. It seems like some information is being lost when trying to add new emails to the list but am unsure exactly what is causing the problem.
First I have a hero component that contains the area of email collection:
const Hero = () => {
const [mail, setMail] = useState(null);
const [loading, setLoading] = useState(false);
//Called onClick()
const subscribe = () => {
setLoading(true);
axios.put("api/sendgrid/mailingList", mail)
.then((result) => {
if (result.status === 200) {
toast.success(result.response.data);
setLoading(false);
}
})
.catch((error) => {
console.log(error.response.data);
setLoading(false);
});
};
The axios put from the previous section goes to my api/sendgrid/mailingList:
import axios from "axios";
export default async function handler(req, res) {
if (req.method === "PUT") {
await axios.put("https://api.sendgrid.com/v3/marketing/contacts", {
contacts: [{ email: req.body.mail }],
list_ids: [process.env.SENDGRID_MAILING_ID],
},
{
headers: {
"content-type": "application/json",
Authorization: `Bearer ${process.env.NEXT_PUBLIC_SENDGRID}`,
},
}
)
.then((res) => {
res.status(200).send({
message:
"Your email has been succesfully added to the mailing list. Welcome 👋",
});
})
.catch((error) => {
res.status(500).send({
message:
"There was a problem with your subscription, please try again or contact us",
});
});
}
}
I am able to access my API script but am met with the following error:
PUT http://localhost:3000/api/sendgrid/mailingList 500 (Internal
Server Error)
The network tab on the console tools:
Related
When a user clicks on pay button in index.html,
form data is sent to the /stk route in server.js
where the form data alongside other parameters are
used as the body of an api request which initiates
an STK push on the user's phone at the same time
a response sent back indicating that the payment has
been accepted for processing. The reponse includes
an ID called 'checkOutRequestId' which is used to make
a transaction status query to establish whether the
user made payment successfully or cancelled based
on response received in /transactionStatus route.
When the current 'checkOutRequestId' is sent as the body in a post
request to /transactionStatus route, I keep catching an error
logged as: trnx attempt fail Request failed with status code 500.
However, when I use 'checkOutRequestId' from any previous process
the kind of response expected from /transactionStatus route is received
without an error only that now the response is for a previous
process and not the current one.
i.e If on clicking the button the process led to the return of
such an ID: checkOutRequestId: ws_CO_06112022153728xxxxxxxxxxx2
, which is then used as the body sent to /transactionStatus
route, an error (500) is caught.
When this same ID (ws_CO_06112022153728xxxxxxxxxxx2) is used as
the body to /transactionStatus route in a new post request.
A response matching that ID is returned successfully.
How do I go about resolving this problem?
Note: I'm trying to work with an api called `Lipa Na MPESA
Online Transaction Query'
//index.html
<form id="myForm" >
<input id="phone" type="number" name="phone" placeholder="Enter phone">
<input id="amount" type="number" name="amount" placeholder="Enter amount" inputmode="numeric">
<!-- <button id="submit">Make payment</button> -->
<button type="submit" id="submit">Pay</button>
</form>
//index.js
const myForm = document.querySelector("#myForm");
let amount = document.querySelector("#amount");
amount.value = 1;
let cash = Number(amount.value);
myForm.addEventListener("submit", function (e) {
e.preventDefault();
const phone = document.querySelector("#phone").value;
const url = "http://localhost:port/stk";
const body = {
phone: phone,
amount: cash,
};
const options = {
method: "POST",
body: JSON.stringify(body),
headers: { "Content-type": "application/json; charset =UTF-8" },
};
fetch(url, options)
.then((res) => {
return res.json();
})
.then((data) => {
console.log("in front", data.CheckoutRequestID);
trnxStatus(data.CheckoutRequestID);
});
});
function trnxStatus(checkoutReqId) {
const checkoutRequestID = checkoutReqId;
const body = {
checkoutReqId: checkoutRequestID,
//if ID from previous process is used here, the process works successfully
// checkoutReqId: "ws_CO_06112022153728xxxxxxxxxxx2",
};
const options = {
method: "POST",
body: JSON.stringify(body),
headers: { "Content-type": "application/json; charset =UTF-8" },
};
const trnxUrl = "http://localhost:port/transactionStatus/";
fetch(trnxUrl, options)
.then((res) => {
return res.json();
})
.then((data) => {
console.log("response data", data);
})
.catch((err) => {
console.log("error message", err.message);
});
}
//server.js
const businessShortCode = process.env.SHORTCODE;
const passKey = process.env.PASSKEY;
let date = new Date();
const timestamp =
date.getFullYear() +
("0" + (date.getMonth() + 1)).slice(-2) +
("0" + date.getDate()).slice(-2) +
("0" + date.getHours()).slice(-2) +
("0" + date.getMinutes()).slice(-2) +
("0" + date.getSeconds()).slice(-2);
const password = new Buffer.from(
businessShortCode + passKey + timestamp
).toString("base64");
app.post("/stk", generateToken, async (req, res) => {
const phone = `254${req.body.phone.substring(1)}`;
const amount = req.body.amount;
await axios
.post(
"https://sandbox.safaricom.co.ke/mpesa/stkpush/v1/processrequest",
{
BusinessShortCode: businessShortCode,
Password: password,
Timestamp: timestamp,
TransactionType: "CustomerPayBillOnline", //"CustomerBuyGoodsOnline"
Amount: amount,
PartyA: phone,
PartyB: businessShortCode,
PhoneNumber: phone,
CallBackURL: "https://011c-179-000-1312-63.ngrok.io/stk_callback",
AccountReference: "Test",
TransactionDesc: "Test",
},
{
headers: {
authorization: `Bearer ${token}`,
},
}
)
.then((data) => {
res.status(200).json(data.data);
})
.catch((err) => {
res.status(400).json(err.message);
});
});
app.post("/transactionStatus", generateToken, async (req, res) => {
const checkoutReqId = req.body.checkoutReqId;
const trnxUrl = "https://sandbox.safaricom.co.ke/mpesa/stkpushquery/v1/query";
await axios
.post(
trnxUrl,
{
BusinessShortCode: businessShortCode,
Password: password,
Timestamp: timestamp,
CheckoutRequestID: checkoutReqId,
},
{
headers: {
authorization: `Bearer ${token}`,
},
}
)
.then((data) => {
res.status(200).json(data.data);
console.log("check data response", data.data);
})
.catch((err) => {
console.log("trnx attempt fail", err.message);
res.status(400).json(err.message);
});
});
const port = process.env.PORT;
app.listen(port, () => {
console.log(`app is running on port ${port}`);
});
who I'm and what I'm trying to do :
I am a beginner following and building a MERN stack project tutorial on youtube
I want to make two requests to the server :
the first request is a register/ signUp request (not working fine).
the second request is a login request (working fine).
errors in my console
POST http://localhost:5000/auth/register 500 (Internal Server Error)
AxiosError {message: 'Request failed with status code 500', name: 'AxiosError', code: 'ERR_BAD_RESPONSE', config: {…}, request: XMLHttpRequest, …}
my console looks like this
source code:
Auth.jsx
const handleSubmit = (e) => {
// setConfirmPass(true);
e.preventDefault();
if (isSignUp) {
data.password === data.confirmpass
? dispatch(signUp(data))
: setConfirmPass(false);
} else {
dispatch(logIn(data));
}
};
AuthRequest.js
import axios from "axios";
const API = axios.create({ baseURL: "http://localhost:5000" });
export const logIn = (formdata) => API.post("/auth/login", formdata);
export const signUp = (formdata) => API.post("/auth/register", formdata);
AuthAction.js
import * as AuthAPI from "../api/AuthRequest.js";
export const logIn = (formData) => async (dispatch) => {
dispatch({ type: "AUTH_START" });
try {
const { data } = await AuthAPI.logIn(formData);
dispatch({ type: "AUTH_SUCCESS", data: data });
} catch (error) {
console.log(error);
dispatch({ type: "AUTH_FAIL" });
}
};
export const signUp = (formData) => async (dispatch) => {
dispatch({ type: "AUTH_START" });
try {
const { data } = await AuthAPI.signUp(formData);
dispatch({ type: "AUTH_SUCCESS", data: data });
} catch (error) {
console.log(error);
dispatch({ type: "AUTH_FAIL" });
}
};
Can somebody tell me why my sighUp request is showing me an error and login is working fine. How to fix that errors.
both request are working fine using thunderclient.
Sorry If I am not able to understand properly here what my problem is. you can open the youtube video link (at time 45:44). this is what I'm trying to do. I have added the cors package also but for the sighup request it is not working.
I have a simple project going on and it is smoothly working but I have failed to add a item delete button. My post request to add items is perfectly working but my delete items doesn't work. I chose to go with post instead of delete because of my api structure.
Repo: https://github.com/berkaydagdeviren/rl-revenue-calculator
const handleClick = async (e) => {
e.preventDefault();
console.log(totalCredit, 'total credit before')
setTotalCredit([...totalCredit, credit])
console.log(ref, 'refFFFFFFF')
const currentDate = ref.current
const options = {
method: "PUT",
headers: {
'Content-type': 'application/json'
},
body: JSON.stringify(
{ date: currentDate, credits: credit }
)
}
var responseClone;
fetch(`api/hello?date=${ref.current}`, options)
.then(res => {
responseClone = res.clone();
return res.json()
}).then(data => {
console.log(data, 'data')
}).then(function (data) {
// Do something with data
}, function (rejectionReason) { // 3
console.log('Error parsing JSON from response:', rejectionReason, responseClone); // 4
responseClone.text() // 5
.then(function (bodyText) {
console.log('Received the following instead of valid JSON:', bodyText); // 6
});
});
setCredit(0)
}
This is working perfectly fine but this does not;
const handleItemDelete = async itemToBeDeleted => {
console.log(itemToBeDeleted, "itemTobeDeleted")
const options = {
method: "PUT",
headers: {
'Content-type': 'application/json'
},
body: JSON.stringify(
{ date: ref.current, index: itemToBeDeleted }
)
}
var responseClone;
await fetch(`api/hello?date=${ref.current}`, options)
.then(async res => {
responseClone = res.clone();
console.log(res, "res")
return await res.json()
// I used this to read server's response when it was giving parsing JSON error
}).then(data => {
console.log(data, 'data')
}).then(function (data) {
// Do something with data
}, function (rejectionReason) { // 3
console.log('Error parsing JSON from response:', rejectionReason, responseClone); // 4
responseClone.text() // 5
.then(function (bodyText) {
console.log('Received the following instead of valid JSON:', bodyText); // 6
});
});
const newTotalCredit = await data.find(item => item.date == ref.current).credits
setTotalCredit(newTotalCredit)
console.log("STATE UPDATED BEFORE DATA")
}
This is where I reference handleItemDelete to;
credit.map((item, index) => {
return (
item > 0 ?
React.Children.toArray(
<div>
<span style={{ color: 'green' }}> +{item}C </span>
<button onClick={() =>handleItemDelete(index)}>
X
</button>
</div>
)
:
null
)
})
}
And this is how I handle put request, again I can see that mongodb is updated after refresh but because ui didn't totalCredits' indexes are messed up and results in either no deletion or false deletion.
handler.put(async (req, res) => {
let data = req.body
console.log(typeof(data))
if (data.index) {
let {date, index} = req.body
console.log(data.index, "data.index")
await req.db.collection('credits').update({date: date}, {$unset: {["credits."+ index] : 1}})
await req.db.collection('credits').update({date: date}, {$pullAll: {credits: [null]}})
}
await req.db.collection('credits').updateOne({date: data.date}, {$push: {credits: data.credits}})
res.json(data)
})
I use SWR right in the index.js Home component
export default function Home()
{
const [totalCredit, setTotalCredit] = useState([])
const [credit, setCredit] = useState('')
const ref = useRef(null);
const [date, setDate] = useState(null);
const { data } = useSWR('/api/hello', async (url) => {const response = await axios.get(url);
return response.data; },
{ refreshInterval: 1000, revalidateOnMount: true });
Sorry if I'm not clear or providing wrong pieces of code please let me know. Thank you in advance!
your options in handleDeleteItem:
const options = {
method: "PUT",
headers: {
'Content-type': 'application/json'
},
Should not method be DELETE? You are sending PUT request instead of DELETE
I am passing a parameter to the axios get request. It works on postman properly but does not work with my code. I don't know where I am making a mistake.
I want only one specific data from db but I am receiving all the data in available in the collection. But with postman I get the desired data
backend route :
router.get('/displayUser', (req,res) => {
const query = user = req.body ;
Services.find(query)
.exec((err, services) => res.json(services))
})
axios call : I tried two different ways and both didn't work
method 1:
getData: async function () {
const user = this.userId
console.log(user)
let res = await axios.get('http://localhost:5000/api/services/displayUser' , { params: { user }})
console.log(res.data);
}
method 2:
getData: async function () {
var data = JSON.stringify({"user":this.userId});
console.log(data)
var config = {
method: 'get',
url: 'http://localhost:5000/api/services/displayUser',
headers: {
'Content-Type': 'application/json'
},
data : data
};
axios(config)
.then(function (response) {
console.log(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
});
}
When I get the data in console I am getting all 3 objects available in collection instead of the specific one related to the user Id
Screenshot
But in postman It works as desired
screenshot
I do this as following:
when I need a get :
app.get('/detail/:id', function (req, res) {
//console.log(req.params.id);
var url=urlDetail + "/" + req.params.id;
axios.get(url)
.then(function (response) {
// result=response.data;
res.render('database', { title: 'Detail' , dbs: response.data ,Version:pjson.version});
})
.catch(function (error) {
// handle error
console.log(error);
})
.then(function () {
// always executed
//console.log("ici always");
});
});
and when i need to post (req.body is a json):
app.post('/carto/demande', function (req, res) {
let data;
console.log(req.params);
console.log(req.body);
var url=urlCartoDemande;
axios.post(url,req.body)
.then(function (response) {
data=response.data;
res.render('carto', { title : 'Demande' ,Version:pjson.version,mode:"resultat",data:data } );
})
.catch(function (error) {
// handle error
console.log(error);
})
.then(function () {
// always executed
});
});
I am following a tutorial from Coding Garden. There he writes to a database and sends it then back to the client.
When I try to do it, I do not get a respond from the server. I guess there has been a mix up in my code.
When I go to localhost/5000/posts there is no database. Why do I not get an errormessage, or a database?
Best regards
Expected Result:
https://youtu.be/JnEH9tYLxLk?t=3060
client code
const form = document.querySelector('form');
const loadingElement = document.querySelector(".loading");
const API_URL = "http://localhost:5000/posts";
loadingElement.style.display = "none";
form.addEventListener('submit', (event) => {
event.preventDefault();
const formData = new FormData(form);
const name = formData.get('name');
const content = formData.get('content');
const post = {
name,
content
};
form.style.display = "none";
loadingElement.style.display= "";
fetch(API_URL, {
method: "POST",
body: JSON.stringify(post),
headers: {
"content-type": "application/json"
}
}).then(response => response.json())
.then(createdPost => {
console.log(createdPost);
});
});
server code
const express = require("express");
const cors = require('cors');
const monk = require("monk");
const app = express();
const db = monk("localhost/posts");
const posts = db.get("posts");
app.use(cors());
app.use(express.json());
app.get("/", (req, res) => {
res.json({
message: "Post"
});
});
function isValidPost(post){
return post.name && post.name.toString().trim() !== "" &&
post.content && post.content.toString().trim() !=="";
}
app.post("/posts", (req, res) => {
if (isValidPost(req.body)){
const post = {
name: req.body.name.toString(),
content: req.body.content.toString(),
created: new Date()
};
//console.log(post);
posts
.insert(post)
.then(createdPost => {
res.json(createdPost);
});
}else {
res.status(422);
res.json({
message: "Hey, Titel und Inhalt werden benötigt!"
});
}
});
app.listen(5000, () => {
console.log('Listening on http://localhost:5000');
});
You forgot to handle the case when post.insert(...) fails and rejects. In this case no response is sent from your server and the request will hang. Add the following:
posts
.insert(post)
.then(createdPost => {
res.json(createdPost);
})
.catch(err => {
console.log(err);
res.status(500).json({errorMessage: err.message});
});
handle the fetch method with catch. It probably goes to catch.
fetch().then().catch(err => ...)