Service ID invalid when trying to use EmailJS with React - javascript

I created a form to contact me on my website, for that I use EmailJS.
However when I try to send myself a mail through the contact form I got a 400 Error The service ID is invalid.
I followed every steps of that tutorial as I haven't use EmailJS before https://blog.mailtrap.io/react-send-email/
Here is my Contact component
class Contact extends React.Component {
constructor(props) {
super(props);
this.state = { feedback: '', name: 'Name', email: 'email#example.com' };
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
render() {
return (
<form className="test-mailing">
<h1>Let's see if it works</h1>
<div>
<textarea
id="test-mailing"
name="test-mailing"
onChange={this.handleChange}
placeholder="Post some lorem ipsum here"
required
value={this.state.feedback}
style={{width: '100%', height: '150px'}}
/>
</div>
<input type="button" value="Submit" className="btn btn--submit" onClick={this.handleSubmit} />
</form>
)
}
handleChange(event) {
this.setState({feedback: event.target.value})
}
handleSubmit() {
const templateId = 'template_id';
this.sendFeedback(templateId, {message_html: this.state.feedback, from_name: this.state.name, reply_to: this.state.email})
}
sendFeedback (templateId, variables) {
window.emailjs.send(
'gmail', templateId,
variables
).then(res => {
console.log('Email successfully sent!')
})
// Handle errors here however you like, or use a React error boundary
.catch(err => console.error('Oh well, you failed. Here some thoughts on the error that occured:', err))
}
}
And here is what I added in my index.html
`<script type="text/javascript"
src="https://cdn.jsdelivr.net/npm/emailjs-com#2.3.2/dist/email.min.js"></script>
<script type="text/javascript">
(function(){
emailjs.init("my_user_ID_here"); // Obtain your user ID at the dashboard https://dashboard.emailjs.com/integration
})();
`

To fix this, I had to swap out 'gmail' with my service ID.
sendFeedback (templateId, variables) {
window.emailjs.send(
***serviceID here***, templateId,
variables
).then(res => {
console.log('Email successfully sent!')
})
// Handle errors here however you like, or use a React error boundary
.catch(err => console.error('Oh well, you failed. Here some thoughts on the error that occured:', err))
}
The JavaScript console in my web browser helped identify this.

That was happening to me, and it was because I didn't have the account activated.
when you log in, click on 'email services' and select, for example, gmail with your account
pd: google translate

Had the same problem.
To fix it,
I had to paste NOT the 'gmail' string itself but the service_id which
is below the icon gmail
in the EmailJS website after log in. Everyone has its own specific number. Also the template_id is important to put the id generated for your template.
When you want to publish your project it is advisable to place your special ids to the .env file to stay secure.

Please try to check whether you are using the right integration id, check the id token you are using with the one under integration id on the dashboard, this was my issue

Might as well share a quick fix that would probably save someone's time. I just had the same issue while using the code below.
const notifyOwnerOfGuest = async () => {
const userId = 'user_...';
const serviceId = 'service_...';
const templateId = 'template_...';
const accessToken = 'e2e1...';
const postfields = {
user_id: userId,
service_id: serviceId,
template_id: templateId,
accessToken,
};
const response = await fetch('https://api.emailjs.com/api/v1.0/email/send', {
method: 'POST',
body: JSON.stringify(postfields),
// should explicitly add the header content-type here
});
if (!response.ok) throw await response.text();
};
I just explicitly added a Content-type header like so
headers: {
'Content-Type': 'application/json',
},
and now it works.

Related

How do I make a proper search tag?

I am working on a craiglists type application for class. I am a bit stumped on a search bar. Now my page is showing the input bar, and when I type any word, it brings up the entire array of objects, and lists them by title.
My goal is to make it so when text is written in the input, the title of the post will display. for example I type a letter "d" and results of dog will show up. The visible const shows up correctly in my console, and gives me a false or true when a character matches. I just do not know how to make it so it constantly will change on my webpage.
I have some useStates and other things brought in, but don't know if it will be beneficial. I appreciate everyone's help! I am using react, and wondering if filter() could also help me here.
<form>
<input type="text"
onInput={
async (e) => {
const value = e.target.value;
users.forEach(users => {
const visible = users.props.children.props.children.includes(value)
console.log(visible)
})
try {
const response = await axios.get
(`${BASE_URL}/api/${COHORT_NAME}/posts`, {
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`,
},
});
// console.log(response.data.data.posts);
setPosts(response.data.data.posts)
} catch (error) {
console.log('Failed to get posts')
console.error(error)
}
}
} />
</form>
<ul>{
users = posts.map((post) => {
return (
<li id="displaycard" key={post._id}>
<h1>{post.title}</h1>
</li>
);
})
}
</ul>

Cannot upload file and submit it via ngForm in angular

I have a problem with uploading a file from my pc via ngForm as part of a small project I do for a class. It seems that I cannot correctly upload the file as during debugging I get "fakedirectory/name-of-file" rather than the actual temp directory.
I did already search some related posts but they seem to be different than my case and I cannot get them to work.
I would greatly appreciate any help and guidance what can I try next.
I have a frontend part of the project and a separate rest api backend. I will paste the related code here:
HTML:
<form #addOfferForm="ngForm" (ngSubmit)="submitNewOffer(addOfferForm)">
Here I have other text inputs that work fine
...
<input (I tried with ngForm and without) type="file" accept="image/png" id="offerPhoto" (change)="handleOfferPhotoUpload($event)">
...
<button class="public">Publish</button>
Component:
offerPhoto?: File
handleOfferPhotoUpload(event: InputEvent){
const input: HTMLInputElement = event.target as HTMLInputElement;
this.offerPhoto = input.files[0]
console.log( "this.offerPhoto" + this.offerPhoto)
}
addOfferForm: FormGroup = new FormGroup({
offerName: new FormControl(''),
...
offerPhoto: new FormControl(''),
})
submitNewOffer(addOfferForm: NgForm): void {
this.offerService.addOffer$( addOfferForm.value).subscribe({
next: (offer) => {
this.router.navigate(['/offers'])
},
error: (error) => {
console.error(error)
}
})
Service:
addOffer$(body: { offerName: string, ... offerPhoto: File }): Observable<IOffer> //This is an interface that I use {
return this.http.post<IOffer>(`${apiUrl}/offers`, body, { withCredentials: true });
}
Then on the backend I have:
function createOffer(req, res, next) {
const { offerName, buyOrSell, cameraOrLens, offerDescription, offerPhoto, offerContact } = req.body;
const { _id: userId } = req.user;
uploadFile(offerPhoto).then(id => {
const offerPhoto = `https://drive.google.com/uc?id=${id}`
return offerModel.create({ offerName, ... offerPhoto, userId })
.then(offer => res.json(offer))
.catch(next);
})
The uploadFile function worked with a simpler form where I just update a photo that is already there but cannot seem to get the image uploaded as part of the form.
I am very stuck and don't know what else to try.
A very big thanks to anybody who can help me in advance!

CORS No 'Access-Control-Allow-Origin' error in React app w/ Facebook

I'm a junior developer that's fairly new to using Facebook for Developers. I'm hitting a wall with the ReactJs application I'm building and could use your help!
My boss has requested a Grid representation of the Page Plugin, not the actual Plugin itself. For this project, he's requested I make and use a test 'Page' I've found that DevExtreme's Data Grid seems to be the best option in terms of the desired visual, and I'm trying to call my Facebook Page using the Graph API documentation. I know it's hitting at least the area I want it to with my console.log because it's returning the error message.
Here are the errors my browser is returning:
Access to fetch at 'https://www.facebook.com/Feeds-Tester-170107151801959/' from origin 'https://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
GET https://www.facebook.com/Feeds-Tester-170107151801959/ net::ERR_FAILED
The link you'll see referenced in my URL variable has been triple checked to be the correct link. Since I'm using NodeJS, I tried installing the CORS npm package but I'm not 100% sure where to put it to use it, I'm wondering if that's the cause of the issue?
Here's my full code snippet (I'm using VS Code, if that helps):
/*global FB*/
import React from 'react';
import { DataGrid, Editing, Scrolling, Lookup, Summary, TotalItem } from 'devextreme-react/data-grid';
import { Button } from 'devextreme-react/button';
import { SelectBox } from 'devextreme-react/select-box';
import CustomStore from 'devextreme/data/custom_store';
import { formatDate } from 'devextreme/localization';
import 'whatwg-fetch';
const URL = 'https://www.facebook.com/Feeds-Tester-170107151801959/';
const REFRESH_MODES = ['full', 'reshape', 'repaint'];
class Grid extends React.Component {
constructor(props) {
super(props);
this.state = {
fbData: null,
ordersData: new CustomStore({
key: 'OrderID',
load: () => this.sendRequest(`${URL}`, 'GET'),
}),
requests: [],
refreshMode: 'reshape'
};
this.clearRequests = this.clearRequests.bind(this);
this.handleRefreshModeChange = this.handleRefreshModeChange.bind(this);
var body = 'Reading JS SDK documentation';
FB.api('/me/feed', 'post', { message: body }, function(response) {
if (!response || response.error) {
console.log('Error occured');
} else {
console.log('Post ID: ' + response.id);
}
})
}
sendRequest(url, method, data) {
method = method || 'GET';
data = data || {};
this.logRequest(method, url, data);
if(method === 'GET') {
return fetch(url, {
method: method,
credentials: 'include',
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
'Access-Control-Allow-Origin': '*'
}
}).then(result => result.json().then(json => {
if(result.ok) return json.data;
throw json.Message;
}));
}
const params = Object.keys(data).map((key) => {
return `${encodeURIComponent(key) }=${ encodeURIComponent(data[key])}`;
}).join('&');
return fetch(url, {
method: method,
body: params,
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
},
credentials: 'include'
}).then(result => {
if(result.ok) {
return result.text().then(text => text && JSON.parse(text));
} else {
return result.json().then(json => {
throw json.Message;
});
}
});
}
logRequest(method, url, data) {
const args = Object.keys(data || {}).map(function(key) {
return `${key }=${ data[key]}`;
}).join(' ');
const time = formatDate(new Date(), 'HH:mm:ss');
const request = [time, method, url.slice(URL.length), args].join(' ');
this.setState((state) => {
return { requests: [request].concat(state.requests) };
});
}
clearRequests() {
this.setState({ requests: [] });
}
handleRefreshModeChange(e) {
this.setState({ refreshMode: e.value });
}
render() {
const { refreshMode, ordersData } = this.state;
return (
<React.Fragment>
<DataGrid
id="grid"
showBorders={true}
dataSource={ordersData}
repaintChangesOnly={true}
>
<Editing
refreshMode={refreshMode}
mode="cell"
allowAdding={true}
allowDeleting={true}
allowUpdating={true}
/>
<Scrolling
mode="virtual"
/>
<Lookup dataSource={ordersData} valueExpr="Value" displayExpr="Text" />
<Summary>
{/* <TotalItem column="CustomerID" summaryType="count" />
<TotalItem column="Freight" summaryType="sum" valueFormat="#0.00" /> */}
</Summary>
</DataGrid>
<div className="options">
<div className="caption">Options</div>
<div className="option">
<span>Refresh Mode: </span>
<SelectBox
value={refreshMode}
items={REFRESH_MODES}
onValueChanged={this.handleRefreshModeChange}
/>
</div>
<div id="requests">
<div>
<div className="caption">Network Requests</div>
<Button id="clear" text="Clear" onClick={this.clearRequests} />
</div>
<ul>
{this.state.requests.map((request, index) => <li key={index}>{request}</li>)}
</ul>
</div>
</div>
</React.Fragment>
);
}
}
export default Grid;
This is the link to the docs for the module I'm trying to reference
I'm trying to not bite off more than I can chew and just start with retrieving the data before I even think about manipulating it or sending any in return. Any insight or guidance you can provide would be greatly appreciated. Thank you!! :)
Do not use fetch with the Facebook URL, it won't let it happen on the browser, instead, use the Facebook API for everything you need to do with it
For example, instead of fetching the page, use the api with the page
FB.api('/Feeds-Tester-170107151801959', function(response) {
// ...
});
If you need to fetch the page, then you have to do it outside the browser environment or use a proxy like cors anywhere, but you can avoid that by using the Facebook API
I was also getting these error. I found that the pageId, I was using was wrong🤦‍♀️. These errors come only when your pageId is wrong or the domain is not whitelisted properly(I even tried with a ngrok url and it worked😵).
So the steps which I followed were:
In buisness.facebook.com go to inbox from sidebar and select chat plugin. [https://i.stack.imgur.com/rDk5d.png]
Click on setup to add your domain. [https://i.stack.imgur.com/exOi2.png]
Pick a setup method(standard for react/nextjs) and setup chat plugin(add language, domain, copy code and paste it). [https://i.stack.imgur.com/hDArZ.png]
You can add multiple domains. [https://i.stack.imgur.com/zGdgx.png]
You will get pageId already embedded. [https://i.stack.imgur.com/iRT13.png]
Use this code and paste it in _document.js file in nextjs. and after deploying it will work perfectly. For any confusion please let me know. Thanks, Happy Coding ☺

Stripe not being called

I am trying to use Vue.js for my front end to call Stripe and create a token which then is sent to my backend. I have tested everything using plain HTML/JS and it all works fine, my issue comes in trying to use Vue.js I think my issue might be in how I am binding the stripe public key. Below is my code, and I have zero output to speak of, I get just redriected to the same page but wth ? at the end of the URL. Nothing else, console shows nothing and no error message or anything send to my back end.
template code
There is more but not related
<div class="col-md-8">
<card class='stripe-card col-md-8'
:class='{ complete }'
:stripe='stripeKey'
:options='stripeOptions'
#change='complete = $event.complete'
/>
<button class='pay-with-stripe' #click='pay' :disabled='!complete'>Submit Payment Details</button>
<br>
</div>
script section with relavent added
import { Card, createToken } from 'vue-stripe-elements-plus'
import axios from 'axios';
export default {
components: { Card },
data() {
return {
errorMessage: null,
successMessage: null,
complete: false,
stripeKey: process.env.VUE_APP_STRIPE_PUB_KEY,
stripeOptions: {
// see https://stripe.com/docs/stripe.js#element-options for details
hidePostalCode: true
},
current: {
stripe: {
plan: null,
last4: null
}
},
}
},
methods: {
pay () {
createToken().then(result => {
axios.post('/billing/updateCard', {
token: result.token,
})
.then(res => {
if(res.data.success == true) {
this.successMessage = res.data.message
console.log(res.data.message)
}
if(res.data.success == false) {
this.errorMessage = res.data.message // Display error message from server if an error exists
}
})
.catch((err) => {
if(err) console.log(err)
if(err) this.$router.push('/company/settings?success=false')
})
});
}
}
}
</script>
I have checked that the API key is actually in the data value by doing <p>{{ stripeKey }}</p> and seeing the value show up. So yes the key is there and the key is valid (tested copy/paste into my HTML/JS test)
created(){
this.key=process.env.VUE_APP_STRIPE_KEY;
}
try this, i used this piece of code in my project and it worked... the issue maybe is that your key is not yet initialized when card us rendered idk. maybe key isnt issue at all. try this and let me know if works and we will debug it together.

Select option child component not reseting to key 0 on form submit with reactjs

I have a select option child component (called Service) for a form because I am loading the values with a JSON file. Also, I am using event.preventDefault() within my handleSubmit() event so that the react-notifications success message displays correctly, rather than disappearing right away because of the re-render.
This is causing my select option fields to maintain the value that was selected before the form was submitted. I need these to be reset to key 0, so that I have a "fresh" form.
I realize that event.preventDefault() prevents the form from naturally resetting, so I am clearing the state of my form elements after. This does not reset the select options though.
I tried removing event.preventDefault() and this allows the form to reset, but then my react-notification success message does not show.
I have tried placing the react-notification message in a different life cycle method (componentDidUpdate()), but I have not been successful as the success message does not show.
Handle Submit
handleSubmit(event) {
event.preventDefault();
let formData = {
name: this.state.name,
phone: this.state.phone,
email: this.state.email,
service1: this.state.service1,
service2: this.state.service2,
service3: this.state.service3
};
fetch('/emails/requestform', {
method: 'post',
body: JSON.stringify(formData),
headers: {
"Content-Type": "application/json"
}
}).then(
this.createNotification('success'),
this.setState({name: ''}),
this.setState({phone: ''}),
this.setState({email: ''}),
this.setState({service1: ''}),
this.setState({service2: ''}),
this.setState({service3: ''})
).catch(error => console.log(`Error posting form: ` + error));
}
Service Component
import React from 'react';
import './Service.css';
class Service extends React.Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
this.handleSubmitForSelect = this.handleSubmitForSelect.bind(this);
}
handleChange(event) {
this.props.onServicesChange(event.target.value);
}
handleSubmitForSelect(event) {
this.setState(event.target.value = '');
}
render() {
let services = this.props.state.services;
let optionItems = services.map((service) => <option key={service.id} value={service.value}>{service.service}</option>);
return (<div >
<select className="select" value={this.props.value} onChange={this.handleChange} onSubmit={this.handleSubmitForSelect}>
{optionItems}
</select>
</div>)
}
}
export default Service;
I expect the form to fully reset and the react-notification success message to still show. But at the moment it seems like only one or the other is possible.
You need to pass a function argument to then() . Then your business logic goes inside the function
fetch('/emails/requestform', {
method: 'post',
body: JSON.stringify(formData),
headers: {
"Content-Type": "application/json"
}
})
.then((resp) => resp.ok ? resp.json() : Promise.reject('Bad request status = '+ resp.status))
.then((data) => {
// ^^^^^^^^^^ anonymous function argument
// do something with response data here
this.createNotification('success');// <== semi colon not comma
this.setState({
name: '',
phone: '',
email: '',
service1: '',
service2: '',
service3: ''
});
}).catch((err)=> console.error(err))

Categories

Resources