Expressjs Post-request is not getting recognized | 404-Error - javascript

I want to implement paypal to my website, but I am stuck with this. Always when I try to do a post request (also tried with postman), I dont get an answer which is just the normal 404 error-page. The console is showing no error, so I guess the post request is not getting recognized.
What could be the problem and how can I fix it?
server.js
//payment
app.post("/pay", (req, res) => {
// payment data
const create_payment_json = {
"intent": "sale",
"payer": {
"payment_method": "paypal"
},
"redirect_urls": {
"return_url": "http://localhost:3000/success",
"cancel_url": "http://localhost:3000/cancel"
},
"transactions": [{
"item_list": {
"items": [{
"name": "product1",
"sku": "001",
"price": "350.00",
"currency": "USD",
"quantity": 1
}]
},
"amount": {
"currency": "USD",
"total": "350.00"
},
"description": "test"
}]
};
// create payment
paypal.payment.create(create_payment_json, (error, payment) => {
if(error) {
console.log("payment not successful");
console.log(error)
} else {
console.log("payment successful");
console.log(payment);
}
})
})
products.ejs
<form action="/pay" method="post">
<input type="submit" value="add to cart" onclick="window.location.href='/pay'"/>
</form>

Couple of things you need to make sure
Make sure you are sending the post request to the correct port, just incase your express server isn't hosting the actual site as well. If it is then don't worry about the port
You can use js to send the request to prevent the page from refreshing.
const form = document.querySelector('form')
form.addEventListener('submit', async function(e) {
e.preventDefault()
const port = 3000 //make sure this is the port your express erver is listening on
const formData = new FormData(e.target)
const itemId = formData.get('itemId')// You can store the items id in the name attribute of an input
const response = await fetch(`http://localhost:${port}/pay`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({itemId})
})
})
const data = await response.json()
console.log(data) // The response you would get from the server

Related

Trying to grab the correct post id from API in order to send message to only that post

In React Javascript - how would I send a message to a post with a specific id? Here's a sample object:
{
"success": true,
"error": null,
"data": {
"post": {
"location": "Bronx, NY",
"willDeliver": false,
"messages": [],
"active": true,
"_id": "5e8d1bd48829fb0017d2233b",
"title": "Schwinn Bicycle",
"price": "3.88",
"description": "This is a 19 speed bicycle, barely used.",
"author": {
"_id": "5e8d1a02829c8e0017c20b55",
"username": "joe1234"
},
"createdAt": "2020-04-08T00:33:24.157Z",
"updatedAt": "2020-04-08T00:33:24.157Z",
"__v": 0,
"isAuthor": true
}
}
}
I must be grabbing the id incorrectly because the message isn't sending to the right post.
I have a useState initialized with an empty string to store the post id so I can pass it into the fetch URL request.
const [postId, setPostId] = useState("");
const response = await fetch(`${API_URL}/posts/${id}/messages`
Here's the code I have so far
const sendMessage = async (token, id, content) => {
try {
const response = await fetch(`${API_URL}/posts/${id}/messages`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
body: JSON.stringify({
message: {
content: content,
},
}),
});
const data = await response.json();
alert("message successfully sent");
return data;
} catch (err) {
console.error(err);
}
};
<form
name="message"
onSubmit={(event) => {
event.preventDefault();
posts.map((post) => {
setPostId(post._id);
});
}}
<label htmlFor="content">Content: </label>
<input
type="text"
name="content"
value={messageContent}
required
onChange={(event) => {
setMessageContent(event.target.value);
}}
/>
<button
onClick={() => {
sendMessage(token, postId, messageContent);
}}
>
Send
</button>
Thanks for any hints or help!

How to put a buffer in an HTTP request?

I’m trying to put a buffer in a request because I have a list of data to import. I want to have success request after one another. The problem I’m encountering is that it waits to upload all data of the request.
Here is the sample data:
[
{
"contacts": "dsds#dsd.com",
"recipient": "dsd#dsd.com",
"date_sent": "07/08/2020 17:05:04",
"subject": "repurchase"
},
{
"contacts": "asd#ret.com",
"recipient": "test#yahoo.com",
"date_sent": "07/10/2020 17:31:51",
"subject": "biz"
},
{
"contacts": "we#sdf.com",
"recipient": "abc#yahoo.com",
"date_sent": "07/09/2020 13:02:54",
"subject": "rock"
}
];
const createEngage = async(body) => {
const BASE_URL = '/api/import'
var requestOptions = {
method: 'POST',
headers: {
'Accept': 'application/json',
"Content-Type": "application/json"
},
body: body
};
fetch(BASE_URL, requestOptions)
.then(response => response.text())
.then(async result => {
console.log(result);
})
.catch(error => console.log('error', error));
}
What you probably want to do is to loop over your data and use async / await to wait at each iteration. Your implementation of your asynchronous function currently does not await anything. Instead it should await the fetch request and the decoding of the body with response.text().
Check the response for errors and wrap the fetch request in a try...catch block. If an error occurs then the catch block will be executed. Otherwise check the response object for any states or errors you want to include.
const data = [
{
"contacts": "dsds#dsd.com",
"recipient": "dsd#dsd.com",
"date_sent": "07/08/2020 17:05:04",
"subject": "repurchase"
},
{
"contacts": "asd#ret.com",
"recipient": "test#yahoo.com",
"date_sent": "07/10/2020 17:31:51",
"subject": "biz"
},
{
"contacts": "we#sdf.com",
"recipient": "abc#yahoo.com",
"date_sent": "07/09/2020 13:02:54",
"subject": "rock"
}
];
const BASE_URL = '/api/import'
/**
* Sends a request for each individual item.
*/
const createEngage = async body => {
const requestOptions = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body
};
try {
const response = await fetch(BASE_URL, requestOptions);
if (!response.ok) {
alert('Your request has failed');
return null;
}
const text = await response.text();
return text;
} catch(error) {
alert('Your request caused an error');
}
};
/**
* Loop over each item and call createEngage.
* Wait for the request to finish and continue.
*/
const createMultipleEngages = async data => {
for (const item of data) {
const result = await createEngage(item); // This will make the loop wait every time.
console.log(result);
}
};
// Call the function and start looping.
createMultipleEngages(data);

Gmail-API Threads.list is not returning messages in the response

I'm trying to use the Gmail-API to get all the threads from a user and to have all of the messages in that thread by using threads.list. In the gmail documentation, it states that the following is the response from hitting this endpoint:
{
"threads": [
users.threads Resource
],
"nextPageToken": string,
"resultSizeEstimate": unsigned integer
}
I have a simple function to hit this endpoint
const {google} = require('googleapis');
/**
* Lists the threads in the user's account.
*
* #param {google.auth.OAuth2} auth An authorized OAuth2 client.
*/
export function listThreads(auth,fn) {
const gmail = google.gmail({version: 'v1', auth});
gmail.users.threads.list({
userId: 'me',
q: 'to:abc#abc.com '
}, (err, res) => {
if (err) throw 'The API returned an error: ' + err;
// fn is a callback used to return data to the handler since
// the res object is in the callback of thread.list
fn(res)
});
}
The following is what I get as a response (I replaced the actual email with abc and replaced my token for privacy):
{
"gmail": {
"config": {
"url": "https://www.googleapis.com/gmail/v1/users/me/threads?q=to%3Aabc%40abc.com",
"method": "GET",
"headers": {
"Accept-Encoding": "gzip",
"User-Agent": "google-api-nodejs-client/0.7.2 (gzip)",
"Authorization": "Bearer 123456",
"Accept": "application/json"
},
"params": {
"q": "to:abc#abc.com"
},
"responseType": "json"
},
"data": {
"threads": [
{
"id": "173bf0efdd1f1dc4",
"snippet": "Hello abc, Attached are the screenshots of my website for the requirements. Please send me an email with all of the information I'm asking for in the forms. For the colors, here is the site to",
"historyId": "4759550"
}
],
"resultSizeEstimate": 1
},
"headers": {
"alt-svc": "h3-29=\":443\"; ma=2592000,h3-27=\":443\"; ma=2592000,h3-T050=\":443\"; ma=2592000,h3-Q050=\":443\"; ma=2592000,h3-Q046=\":443\"; ma=2592000,h3-Q043=\":443\"; ma=2592000,quic=\":443\"; ma=2592000; v=\"46,43\"",
"cache-control": "private",
"connection": "close",
"content-encoding": "gzip",
"content-type": "application/json; charset=UTF-8",
"date": "Thu, 20 Aug 2020 01:13:07 GMT",
"server": "ESF",
"transfer-encoding": "chunked",
"vary": "Origin, X-Origin, Referer",
"x-content-type-options": "nosniff",
"x-frame-options": "SAMEORIGIN",
"x-xss-protection": "0"
},
"status": 200,
"statusText": "OK"
}
}
As you can see, the messages property of res.data.threads is completely missing. I would appreciate any guidance.
Thank You
In this case, in order to retrieve all messages from each thread, it is required to use the method of "Users.threads: get". When your script is modified, it becomes as follows.
Modified script:
const gmail = google.gmail({version: 'v1', auth});
gmail.users.threads.list(
{
userId: "me",
q: "to:abc#abc.com ",
},
(err, res) => {
if (err) throw "The API returned an error: " + err;
Promise.all(
res.data.threads.map(({ id }) => {
return new Promise((resolve, reject) => {
gmail.users.threads.get({ userId: "me", id }, (err, res) => {
if (err) rejects(err);
resolve(res.data);
});
});
})
).then((res) => {
fn(res);
});
}
);
Note:
In this modified script, it supposes that you have already been able to retrieve the email using Gmail API.
References:
-Users.threads: list
-Users.threads: get

How can I get the same content in my react native app as in my postman GET?

I'm communicating with a REST server, which should return ( and this is what I get when I use Postman to request it):
{
"organizer": "Fontysgroup2",
"eventStart": "2019-11-25T11:00:00Z",
"eventStop": "2019-11-25T11:00:00Z",
"room": {
"roomName": "Test Room",
"roomEmail": null,
"password": null
}
},
{
"organizer": "Fontysgroup2",
"eventStart": "2019-11-25T11:00:00Z",
"eventStop": "2019-11-25T11:00:00Z",
"room": {
"roomName": "Test Room",
"roomEmail": null,
"password": null
}
}
]
but this block of code of mine :
await fetch('https://gitroom-backend.azurewebsites.net/api/Event', {
headers: {
Authorization: 'Bearer eyJhbGciOiJodHRwOi8vd3d3LnczLm9yZy8yMDAxLzA0L3htbGRzaWctbW9yZSNobWFjLXNoYTI1NiIs',
}
})
.then(res => {
console.log("content"+JSON.stringify(res))
})
}
is returning:
content{"type":"default","status":200,"ok":true,"headers":{"map":{"cache-control":"public, max-age=0","date":"Mon, 25 Nov 2019 13:14:09 GMT","set-cookie":"ARRAffinity=84e8f0e39af3bde1a8c7117e525b046a8722dc904bb8684ace19b555cc8f3590;Path=/;HttpOnly;Domain=gitroom-backend.azurewebsites.net","x-powered-by":"ASP.NET","request-context":"appId=cid-v1:65c12a05-4adc-4521-b71d-69ccdcb78d9f","server":"Microsoft-IIS/10.0","vary":"Accept-Encoding","content-type":"application/json; charset=utf-8","transfer-encoding":"chunked"}},"url":"https://gitroom-backend.azurewebsites.net/api/Event","_bodyInit":{"_data":{"size":331,"offset":0,"blobId":"7592c623-fb09-415e-92f7-a97e75b08d37"}},"_bodyBlob":{"_data":{"size":331,"offset":0,"blobId":"7592c623-fb09-415e-92f7-a97e75b08d37"}}}
How can I access the actual content that I want and which Postman is giving me?
EDIT:
MY Postman:
fetchData = async () => {
const response = await fetch(
"YOUR_URL"
);
const json = await response.json();
}
Now render items iterative using constructor of your data set.
and call in your view by,
{item.YOUR_KEY}

How to do a POST request from within Hubot?

I'm trying to code a Hubot listener that would automatically create a JIRA issue from a specific chat dialogue. Here's the example (I used Hubot-Rocketchat boilerplate code from here: https://github.com/RocketChat/hubot-rocketchat-boilerplate)
module.exports = (robot) => {
robot.hear(/^#alerts (.*)/i, (res) => {
const jiraurl="https://jira.example.com/rest/api/2/issue/"
const jiraproject="ALERTS"
text = res.match[1]
data = JSON.stringify({
"fields": {
"project":
{
"key": `#{jiraproject}`
},
"summary": `#{text}`,
"description": "Задача создана автоматически из RocketChat",
"issuetype": {
"name": "Инцидент"
}
}
})
/* res.reply(data) */
res.reply(`Создаю задачу в JIRA: ${text}`)
robot.http(jiraurl)
.header('Content-Type', 'application/json')
.post(data) (err, response, body) =>
if err
res.send `Ошибка: #{err}`
return
})
}
What would be the proper way to do this?

Categories

Resources