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

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!

Related

Objects are not valid as a React child. If you meant to render a collection of children, use an array

i want to render an email of all the users for testing purpose, In fact i have done that using this method. --- {dataFromApi.map((item, i) => {item.email})} but still it didn't work
const [dataFromApi, setDataFromApi] = useState([]);
const URL = 'http://localhost:5000/users'
const requestOptions = {
method: 'GET',
headers: {
'Content-Type': 'application/json'
},
}
const submit = () => {
const data = fetch(URL, requestOptions);
data.then( (userdata) => {
return userdata.json();
}).then( (data) => {
setDataFromApi(data[0]);
}).catch( (err) => {
console.log(err);
})
}
return (
<div className="login">
<h1 className="loginTitle">Choose a Login Method</h1>
<p>{dataFromApi}</p>
<div className="wrapper">
.
.
.
.
.
here is the API response
[
{
"id": 1,
"email": "test1234#gm.com",
"password": null
},
{
"id": 2,
"email": null,
"password": null
},
{
"id": 3,
"email": "test#123.com",
"password": "12345678"
},
{
"id": 4,
"email": "test#231.com",
"password": "12345678"
},
{
"id": 5,
"email": "test#231.com",
"password": "12345678"
},
{
"id": 6,
"email": "test#231.com",
"password": "12345678"
},
{
"id": 7,
"email": "NEWtest#231.com",
"password": "123"
}
]
but getting this error
react_devtools_backend.js:4012 The above error occurred in the component:
and
react-dom.development.js:14887 Uncaught Error: Objects are not valid as a React child (found: object with keys {id, email, password}). If you meant to render a collection of children, use an array instead.
Like Adam said in the comments, you are trying to pack a collection of things into a tag meant for a single thing. You should iterate over the list rendering a thing for each item.
{dataFromApi.map((item, i) => <p key={i}>{item.email}</p>)}
I got the answer why i'm not getting the expected output because in this code
const submit = () => {
const data = fetch(URL, requestOptions);
data.then( (userdata) => {
return userdata.json();
}).then( (data) => {
setDataFromApi(data[0]); // this will store only one object into an array
}).catch( (err) => {
console.log(err);
})
}
here setDataFromApi(data[0]) will store only 1 object and to access the email from the object, we have to use only dataFromApi.email else dataFromApi will give only object which we can't render so that's why it is giving an error.

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

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

Slack interactive message getting invalid_payload for response_url sent back

I've been doing some work with the Slack API and with their
interactive messages
I post a message with the interactive message attachment here:
export const postMessage = (msg, channel) => {
request({
method: 'POST',
uri: 'https://slack.com/api/chat.postMessage',
headers: {
'content-type': 'application/json;charset=UTF-8',
Authorization: `Bearer ${process.env.SLACKTOKEN}`,
},
body: JSON.stringify({
token: process.env.SLACKTOKEN,
attachments: [
{
"text": "",
"fallback": "If you could read this message, you'd be choosing something fun to do right now.",
"color": "#3AA3E3",
"attachment_type": "default",
"callback_id": "command_selection",
"actions": [
{
"name": "command_list",
"text": "Choose a command",
"type": "select",
"options": [
{
"text": "Register Team",
"value": "registerTeam"
},
{
"text": "Edit Team",
"value": "editTeam"
},
{
"text": "Get By Url",
"value": "getByUrl"
},
{
"text": "Report Issue",
"value": "reportIssue"
},
{
"text": "Find Team",
"value": "findTeam"
},
{
"text": "List Teams",
"value": "listTeams"
}
]
}
]
}
],
text: msg,
channel,
as_user: true,
})
}, (err, res, body) => {
if (err) {
console.log('error posting msg: ', err);
} else {
console.log('post message to channel: ', body);
}
})
}
Slack then sends a POST request to this URL with a response_url parameter in their payload. This is where I'm getting the payload from in my code:
api.post('/interactivity', (req, res) => {
const { body } = req;
const { payload } = body;
const parsedPayload = JSON.parse(payload)
res.send(parsedPayload.response_url)
var message = {
"text": payload.user.name+" clicked: "+payload.actions[0].name,
"replace_original": false,
}
util.sendMessageToSlackResponseURL(parsedPayload.response_url, message)
})
export const sendMessageToSlackResponseURL = (responseURL, JSONmessage) => {
var postOptions = {
uri: responseURL,
method: 'POST',
headers: {
'content-type': 'application/json'
},
json: JSONmessage
}
request(postOptions, (error, res, body) => {
if (error){
console.log(error)
} else {
console.log('post message to channel: ', body);
}
})
}
For some reason though, the response_url is giving an invalid_payload error when I click on the link and I can't figure out if its the payload I'm sending in the original message I posted or something's up with the POST request that Slack sent
The issue is with utility method on line json: JSONmessage which should be body: JSONmessage
Updated code,
export const sendMessageToSlackResponseURL = (responseURL, JSONmessage) => {
var postOptions = {
uri: responseURL,
method: 'POST',
headers: {
'content-type': 'application/json'
},
body: JSONmessage
}
request(postOptions, (error, res, body) => {
if (error){
console.log(error)
} else {
console.log('post message to channel: ', body);
}
})
}
Hope this works!

fetch() api method POST sends to many data

I have problem with sending data via POST method in fetch(). So the problem is that from this >> body: JSON.stringify({ id: uuid(), name, password }) it sends couple of times almost the same data (i receive unique id, and diplicated name and password). In the othet words: with one form submission, I've got few objects with differnt id, and same name and password. Code:
const handleSubmit = e => {
e.preventDefault();
users.map(user =>
user.name !== name && name.length >= 3 && password.length >= 5
? fetch('http://localhost:3003/users', {
method: 'POST',
body: JSON.stringify({ id: uuid(), name, password }),
headers: {
'Content-Type': 'application/json'
}
})
.then(res => {
if (res.ok) {
return res.json();
}
throw new Error('Error');
})
.then(c => setUser([...users, c]))
.then(errorUserChange(false))
: errorUserChange(true)
);
};
db.json:
{
"users": [
{
"id": "c1a10ab0-24c7-11ea-af77-3b28fe4ea407",
"name": "cccccc",
"password": "cccccc"
},
{
"id": "cbf73890-24c7-11ea-af77-3b28fe4ea407",
"name": "kkkkkkk",
"password": "kkkkk"
},
{
"id": "cbf786b0-24c7-11ea-af77-3b28fe4ea407",
"name": "kkkkkkk",
"password": "kkkkk"
}
]
}
Of course I know that's not the best way to hold password, I'm just practicing json server and fetch().
Thanks for any help!

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}

Categories

Resources