React,js + Prisma better way to update sql with a button - mysql

async function change_status(object_id:number){
const response = await fetch('/api/db', {
method: 'POST',
body: JSON.parse(`{"id":${object_id}}`)
});
if (!response.ok){
throw new Error(response.statusText);
}
return await response.json();
}
I want this button to change an int in mysql
<button onClick={() => change_status(object.id)}>
change Status
</button>
/api/db.ts
export default async function handler(req: NextApiRequest,res: NextApiResponse) {
const data = JSON.parse(req.body);
const object_id = data.id;
const find_object = await prisma.objects.findFirstOrThrow({
where: {id:object_id}
});
if (find_object.status == 0){
var change = await prisma.objects.update({
where: { id: object_id },
data: { status:1 },
})
}
else {
var change = await prisma.objects.update({
where: { id: object_id },
data: { status:0 },
})
}
res.json(change);
}
I get this error SyntaxError: Unexpected token o in JSON at position 1
Is there any better way to code the button or pass object_id without a JSON

Change your fetch to
const response = await fetch('/api/db', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({ id: object_id }),
});
And in your api simply
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
const { id } = req.body;
...
}

I'm just gonna drop some information about Prisma when I had these kinda problems with it.
1 - don't forget to use body: JSON.stringify(), (this might be the issue here)
2 - config your header as well.
3 - I would suggest avoiding the var keyword because of some sort of things ( like hoisting).
4 - stick with Prisma documentation.they almost covered everything

Related

i am trying to get the response from passport.js from node js to react js,i am sending the access and refresh token once user logi's in with google

i am trying to get the response from passport.js from node js to react js,i am sending the access and refresh token once user logi's in with google but i am not sure how to take response from node to react
React Code
const googleAuth = async () => {
window
.open('http://localhost:4000/oauth/google', '_self')
};
Node Code
I can able to verify the user and generate access and refresh token but i am not sure how to get these response in react
passport.use(
new GoogleStrategy(
{
clientID: GOOGLE_CLIENT_ID,
clientSecret: GOOGLE_CLIENT_SECRET,
callbackURL: "/google/callback",
},
async function (accessToken, res, refreshToken, profile, done) {
done(null, profile);
const enteredemail = profile.emails.map((a) => a.value);
const sftoken = await getSfToken();
var configHeaders = {
method: "get",
headers: {
Authorization: `Bearer ${sftoken}`,
"Content-Type": `application/json`,
},
};
const emailcheck = await axios.get(
`URL`,
configHeaders
);
if (emailcheck.data.success === true) {
const logintoken = await axios.get(
"URL"
);
const acctok = logintoken?.data?.access_token;
const url = `URL`;
const res = await axios.post(
url,
{},
{
headers: {
Authorization: `Bearer ${acctok}`,
},
}
);
const refreshTokenURL = `URL`;
const refresTok = await axios.get(refreshTokenURL, {
headers: {
Authorization: `Bearer ${acctok}`,
},
});
console.log("refreshToken", refresTok);
} else {
return null
}
}
)
);
passport.serializeUser((user, done) => {
done(null, user);
});
passport.deserializeUser((user, done) => {
done(null, user);
});

Unable to fetch data from server due to serialization problem using NextJS?

I'm currently using axios and NextJS.
I currently have this code in my component:
export async function getServerSideProps(context) {
const data = await getVideo(context.query.id);
console.log('data: ', data);
// console.log('context: ', context);
console.log('context params: ', context.params);
console.log('context query: ', context.query);
if (!data) {
return { notFound: true };
}
return {
props: {
videoId: context.params.id,
videoSlug: context.params.slug,
videoContent: data
}
};
}
This getserverSideProps call the function of getVideo which looks exactly like this:
export const getVideo = (id) => async (dispatch) => {
dispatch({ type: CLEAR_VIDEO });
try {
console.log('Action file: ', id);
const res = await api.get(`/videos/${id}`);
return dispatch({
type: GET_VIDEO,
payload: res.data
});
} catch (err) {
dispatch({
type: VIDEO_ERROR,
payload: { msg: err.response?.statusText, status: err.response?.status }
});
}
};
Said function goes through my api function to make requests to backend:
import axios from 'axios';
import { LOGOUT } from '../actions/types';
import { API_URL } from '../config';
const api = axios.create({
baseURL: `${API_URL}/api/v1`,
headers: {
'Content-Type': `application/json`
}
});
/**
intercept any error responses from the api
and check if the token is no longer valid.
ie. Token has expired
logout the user if the token has expired
**/
api.interceptors.response.use(
(res) => {
res;
console.log('Res: ', res.data);
},
(err) => {
if (err?.response?.status === 401) {
typeof window !== 'undefined' &&
window.__NEXT_REDUX_WRAPPER_STORE__.dispatch({ type: LOGOUT });
}
return Promise.reject(err);
}
);
export default api;
It works great when doing POST, PUT,PATCH requests.
As you can see, I'm doing a console.log('data: ',data) but it returns [AsyncFunction (anonymous)] whenever I read the terminal; on the other hand, the front-end returns this error:
Server Error Error: Error serializing .videoContent returned from
getServerSideProps in "/videos/[id]/[slug]". Reason: function
cannot be serialized as JSON. Please only return JSON serializable
data types.
Does anyone knows how to solve this?
NOTE: I'm using react-redux, redux and next-redux-wrapper.
That is because your getVideo function returns another function. The right way to call it would be:
const data = await getVideo(context.query.id)()//<- pass in the dispatch here
But you should not use redux in the backend like that. I think you can completely remove it.
export const getVideo async (id) => {
try {
console.log('Action file: ', id);
const res = await api.get(`/videos/${id}`);
return res.data
});
} catch (err) {
return { msg: err.response?.statusText, status: err.response?.status }
}
};
// call
const data = await getVideo(context.query.id)

how to fetch large json from a post in angular6/7

I have migrated a piece of code to be able to export data as excel file in angular.
I assume the fact that the json is well formed and send from the server to the angular side. I can see it in the network frame in th browser.
For small json, it's ok but when the size of the json starts to be large, the answer still failed.
This following code corresponding to the service call
exportSynthesis(recordId: number, moduleId: number) {
const body = null;
return this.http.post(this.apiUrl + `/data`
+ `${recordId}/module/${moduleId}`, body,
{
headers: new HttpHeaders({ 'Content-Type': 'application/json' }),
observe: 'response', responseType: 'json' }).pipe(
map((resp: any) => {
return resp.body;
}));
}
and here, its the method which manages the return.
exportSynthesis() {
this.service.exportSynthesis(this.recordId, this.moduleId)
.subscribe(
(exportResult) => { this.exportResult = exportResult; },
err => {
console.log('err:', err);
this.errorHandlerService.handleError('failed', err);
},
() => {
console.log('json:', this.exportResult);
const worksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(this.exportResult);
const workbook: XLSX.WorkBook = { Sheets: { 'data': worksheet }, SheetNames: ['data'] };
const excelBuffer: any = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
const blob = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8' });
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = '(GEO) ' + this.record.label + ' - name.xlsx';
a.click();
window.URL.revokeObjectURL(url);
a.remove();
});
}
Currently, i do not manage to understand why it still finish in error and I get only "ok" in the console log.
Any idea?
regards
Angular's HttpClientModule default response is a json.
Your problem is that you try to access the body property of the HTTP response, but Angular interprets that as you trying to access the body property in the body of the response.
Remove observe and responseType from your post request and treat the response as a json. It should work.
find:
just need to use text as json
return this.http.post(this.apiUrl + `/geo/v1/synthesis/xls/record/`
+ `${recordId}/module/${moduleId}`, body,
{
headers: headers,
observe: 'response',
responseType: 'text' as 'json'}).
map((resp: any) => {
return resp.body;
});
}

My response from api is undefined on frontend

I got list of items from my database mySql and also button 'edit'.
When I clicked edit (by id) I want to see all fields filled by data.
But I only have in my console: undefined
If I tested my api by postman it works fine.
There is how I am getting list.
{
const id = this.actRoute.snapshot.paramMap.get('id');
this.studentApi.GetStudent(id).subscribe((res: any) => {
console.log(res.data);
this.subjectArray = res.data;
console.log(this.subjectArray);
this.studentForm = this.fb.group({
id: [res.id, [Validators.required]],
domain_id: [res.domain_id, [Validators.required]],
source: [res.source, [Validators.required]],
destination: [res.destination]
});
});
}
There is my api.service.ts
GetStudent(id): Observable<any> {
const API_URL = `${this.endpoint}/read-student/${id}`;
return this.http.get(API_URL, { headers: this.headers })
.pipe(
map((res: Response) => {
return res || {};
}),
catchError(this.errorMgmt)
);
}
And there is my route
studentRoute.get('/read-student/:id', (request, response) => {
const id = request.params.id;
con.query('SELECT * FROM students WHERE id = ?', id, (error, result) => {
if (error) throw error;
response.send(result);
});
});
There is response from 'postman'
[
{
"id": 5,
"domain_id": 2,
"source": "tester0700#test.pl",
"destination": "testw#test.pl"
}
]
It seems like the response is an array, containing an object.
In that case, there is no need to use res.data, as that would imply the returned observable, res has a property named data, and that you are trying to access the value within that property. You can simply assign res to the subjectArray property. I am pretty sure res would be defined.
this.studentApi.GetStudent(id).subscribe((res: any) => {
console.log(res);
this.subjectArray = res;
// handle the rest here.
});

Trying to get the gender using facebook Messenger Bot call

Hi I am trying to get the gender back from a curl request in node.js.
I am following these instructions https://developers.facebook.com/docs/messenger-platform/user-profile
my code is below, but i get an error during the execution.
I call the below using fbUserInfo(recipentId).catch(console.error);
const fbUserInfo = (id) => {
//const body = JSON.stringify({
// recipient: { id },
// message: { text },
//});
const qs = 'access_token=' + encodeURIComponent(FB_PAGE_TOKEN1);
return fetch('https://graph.facebook.com/v2.6/' + id + '?fields=first_name,last_name,profile_pic,locale,timezone,gender&' + qs, {
method: 'POST',
headers: {'Content-Type': 'application/json'},
//body,
})
.then(rsp => rsp.json())
.then(json => {
if (json.error && json.error.message) {
throw new Error(json.error.message);
}
return json;
});
console.log('=== ' + json); // I was hoping this would output the returned json
}; // const