How to connect slazzer api in react and node - javascript

I am trying to remove the background from the image using slazzer api but got stock due to the error of:
App.js:14 Uncaught (in promise) TypeError: slazzer__WEBPACK_IMPORTED_MODULE_1__.Slazzer is not a constructor
How can I fix the error and make the api work in my code.
Here is the client/app.js :
import React, { useState } from 'react';
import { Slazzer } from 'slazzer';
const App = () => {
const [imageFile, setImageFile] = useState(null);
const [imageUrl, setImageUrl] = useState(null);
const handleFileSelect = e => {
setImageFile(e.target.files[0]);
}
const handleRemoveBackground = async () => {
// initialize Slazzer with your API key
const slazzer = new Slazzer('MY_API_KEY');
// remove the background of the image
const result = await slazzer.removeBackground(imageFile);
// update the state with the new image URL
setImageUrl(result.url);
}
return (
<div>
<input type="file" onChange={handleFileSelect} />
<button onClick={handleRemoveBackground}>Remove Background</button>
{ imageUrl && <img src={imageUrl} alt="Image with removed background" /> }
</div>
);
}
export default App;
Here is the server/index.js
import express from 'express';
import fetch from 'node-fetch';
const app = express();
app.use(express.json());
app.post('/remove-background', async (req, res) => {
try {
// Get the image file from the request
const image = req.body.image;
// Call the Slazzer API to remove the background
const response = await fetch('https://api.slazzer.com/v2.0/remove_image_background', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'api-key': 'MY_API_KEY'
},
body: JSON.stringify({
image: image
})
});
// Get the JSON response from the API
const json = await response.json();
// Send the image url to the client
res.json({ imageUrl: json.url });
} catch (err) {
// Handle any errors
res.status(500).json({ error: err.message });
}
});
app.listen(3001, () => {
console.log('Server started on http://localhost:3001');
});

Related

async await resolve graphql query promise not resolved

Hi All i am trying to use graphql api to fetch some country. I am using this API https://studio.apollographql.com/public/countries/home?variant=current and this is playground https://countries.trevorblades.com/
The problem i am facing is that i cannot resolve the Promise. I am using React and fetch method.
my fetchCountries.js file:
import { API_URL } from "./constants";
const COUNTRIES_QUERY = `{
country(code: "BR") {
name
native
emoji
currency
languages {
code
name
}
}
}`;
const fetchCountries = async () => {
await fetch(API_URL, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
query: COUNTRIES_QUERY,
}),
})
.then((response) => {
if (response.status >= 400) {
throw new Error("Error fetching data");
} else {
return response.json();
}
})
.then((data) => data.data);
};
export default fetchCountries;
i am using async, await in the function so that it gets resolved when i call it. Now in my App.js when i call fetchCountries function in console.log i get :
Promise {<pending>}
[[Prototype]]
:
Promise
[[PromiseState]]
:
"fulfilled"
[[PromiseResult]]
:
undefined
App.js:
import "./App.css";
import fetchCountries from "./api/fetchCountries";
const App = () => {
console.log("CONSOLE LOG API", fetchCountries());
return <div>App</div>;
};
export default App;
I have also tried to use useEffect hook but got the same result:
import "./App.css";
import fetchCountries from "./api/fetchCountries";
import React, { useEffect, useState } from "react";
const App = () => {
const [test, setTest] = useState();
console.log("CONSOLE LOG API", fetchCountries());
useEffect(() => {
const getCountries = async () => {
await fetchCountries();
};
setTest(getCountries());
}, []);
console.log("USE EFFECT API", test);
return <div>App</div>;
};
export default App;
You should do it as follows
const fetchCountries = async () => {
const response = await fetch(API_URL, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
query: COUNTRIES_QUERY,
}),
})
if (response.status >= 400) {
throw new Error("Error fetching data");
} else {
return await response.json();
}
};
export default fetchCountries;
Or enclose entire fetch.then... chain inside paranthesis.

req.query is undefined in Next.js API route

I'm trying to do a delete request. I can fetch the API route through pages/api/people/[something].js.
And this is the response I got from the browser's console.
DELETE - http://localhost:3000/api/people/6348053cad300ba679e8449c -
500 (Internal Server Error)
6348053cad300ba679e8449c is from the GET request at the start of the app.
In the Next.js docs, for example, the API route pages/api/post/[pid].js has the following code:
export default function handler(req, res) {
const { pid } = req.query
res.end(Post: ${pid})
}
Now, a request to /api/post/abc will respond with the text: Post: abc.
But from my API route pages/api/people/[something].js, something is undefined.
const { something } = req.query
UPDATED POST:
React component
export default function DatabaseTableContent(props) {
const id = props.item._id; // FROM A GET REQUEST
const hide = useWindowSize(639);
const [deletePeople] = useDeletePeopleMutation();
async function deleteHandler() {
await deletePeople(id);
}
return <Somecodes />;
}
apiSlice.js
export const apiSlice = createApi({
// reducerPath: "api",
baseQuery: fetchBaseQuery({ baseUrl: url }),
tagTypes: ["People"],
endpoints: (builder) => ({
getPeople: builder.query({
query: (people_id) => `/api/people/${people_id}`,
providesTags: ["People"],
}),
deletePeople: builder.mutation({
query: (studentInfo) => ({
url: `api/people/people-data/student-info/${studentInfo}`,
method: "DELETE",
headers: {
accept: "application/json",
},
}),
invalidatesTags: ["People"],
}),
}),
});
export const {
useGetPeopleQuery,
useDeletePeopleMutation,
} = apiSlice;
pages/api/people/people-data/student-info/[studentInfo].js
import { ObjectId, MongoClient } from "mongodb";
async function handler(res, req) {
const { studentInfo } = req.query; // the code stops here because "studentInfo" is undefined
const client = await MongoClient.connect(process.env.MONGODB_URI.toString());
const db = client.db("people-info");
if (req.method === "DELETE") {
try {
const deleteData = await db
.collection("student_info")
.deleteOne({ _id: ObjectId(studentInfo) });
const result = await res.json(deleteData);
client.close();
} catch (error) {
return res.status(500).json({ message: error });
}
}
}
export default handler;
The order of params passed to your handler functions needs to be reversed.
For NextJS API routes the req is the first param passed to the handler and the res param is second.
Example handler function from NextJS documentation:
export default function handler(req, res) {
res.status(200).json({ name: 'John Doe' })
}

how to pass parameter from client side to node-get request

i have a problem.
i have an object in my client side witch have to be my params.
anyone know how to pass an object from client side to server side?
this is my node route, i need to use endPoint from user to do query params
const fetch = require("node-fetch");
async function getDataByEndPoint(req, res, endPoint) {
const url = "https://pixabay.com/api/?key=<KEY-GOES-HERE>";
const options = {
method: "GET",
// headers: {
// "X-RapidAPI-Host": "famous-quotes4.p.rapidapi.com",
// "X-RapidAPI-Key": "your-rapidapi-key",
// },
};
try {
let response = await fetch(url, options);
response = await response.json();
res.status(200).json(response);
console.log(res);
} catch (err) {
console.log(err);
res.status(500).json({ msg: `Internal Server Error.` });
}
}
module.exports = getDataByEndPoint;
this is my client side code
function App() {
const data = useSelector((state) => state.counter.data);
const endPoint = useSelector((state) => state.counter.endPoint);
const dispatch = useDispatch();
// const [data, setData] = useState([]);
const getData = async (endPoint) => {
const requestOptions = {
method: "GET",
};
try {
const res = await fetch(
`http://localhost:8000/dataByParams`,
requestOptions
);
const resJson = await res.json();
console.log(resJson);
dispatch(setData(resJson.hits));
} catch (err) {
console.log(err);
}
};
unfortunately i cant do
?params=
be because i used node fetch so its doesn't work on my localhost....
i tried to use params on https://pixabay.com/api/?key=<KEY-GOES-HERE>
and its worked but when i use it on local host it doesn't because its not the full url, its just the local host

How can I use axios.defaults.baseURL conditionally? [duplicate]

I am having a config file . where i am setting the baseURL for the entire app and also saving the bearer token for the entire API requests. Here i am in situation to add another api . I dont know how to add another baseURL & use this on my API requests.Here i am sharing the code of what i have done.
BASE URL FILE:
import axios from 'axios';
axios.defaults.baseURL = http://localhost:3000/summary;
const setAuthToken = (token) => {
if (token) {
axios.defaults.headers.common.Authorization = `Bearer ${token}`;
} else {
delete axios.defaults.headers.common.Authorization;
}
};
export default setAuthToken;
API ACTION FILE:
export const login = ({ email, password }) => async (dispatch) => {
const userData = {
username: email,
password,
};
try {
const res = await axios.post('/license-api/auth/login', userData, config);
dispatch({
type: LOGIN_SUCCESS,
payload: res.data.token,
});
} catch (error) {
dispatch({
type: LOGIN_FAIL,
});
}
};
i need to add another url like this in BASE URL FILE
axios.defaults.baseURL = http://localhost:6000/profile
how to add this one and use this in API action file.
Please help me with this.
Thanks in advance
As said you could create two instances of axios and use them as needed:
In you BASE URL file:
import axios from 'axios';
const setAuthToken = (token) => {
if (token) {
axios.defaults.headers.common.Authorization = `Bearer ${token}`;
} else {
delete axios.defaults.headers.common.Authorization;
}
};
const mainAxios = axios.create({
baseURL: 'http://localhost:3000/summary'
});
const profileAxios = axios.create({
baseURL: 'http://localhost:6000/profile'
});
export default setAuthToken;
export { mainAxios, profileAxios };
Then in your API ACTION file:
import { profileAxios } from 'path/to/baseurl';
export const login = ({ email, password }) => async (dispatch) => {
const userData = {
username: email,
password,
};
try {
const res = await profileAxios.post('/license-api/auth/login', userData, config);
dispatch({
type: LOGIN_SUCCESS,
payload: res.data.token,
});
} catch (error) {
dispatch({
type: LOGIN_FAIL,
});
}
};
The above code works well. I don't see where setAuthToken is called so if you don't want to call setAuthToken manually then you might want to do this.
import axios from "axios";
import { config } from "./config";
const pythonAPI = axios.create({
baseURL: config.pythonServerUrl,
});
const nodeApi = axios.create({
baseURL: config.nodeServerUrl,
});
const setToken = () => {
const token = localStorage.getItem("auth_token");
if (token) {
pythonAPI.defaults.headers.common.Authorization = `Basic ${token}`;
} else {
delete pythonAPI.defaults.headers.common.Authorization;
}
};
const pythonApi = {};
pythonApi.get = async (url) => {
setToken();
return pythonAPI.get(url).catch((e) => e.response);
};
pythonApi.post = async (url, data) => {
setToken();
return pythonAPI.post(url, data).catch((e) => e.response);
};
export { pythonApi, nodeApi };

Django + React Axios instance header conflict?

I have all my functions based views on django protected with #permission_classes([IsAuthenticated]) so I have to send a JWT as Bearer token on every request.
In the first version I was using this code:
import axios from 'axios';
import { decodeUserJWT } from '../../extras'
const user = JSON.parse(localStorage.getItem("user"));
var decoded = decodeUserJWT(user.access);
var user_id = decoded.user_id
const instance = axios.create({
baseURL: 'http://localhost:8000/api',
headers: {Authorization: 'Bearer ' + user.access},
params: {userAuth: user_id}
});
export default instance;
Everything was working fine.
But then I added interceptors so I could handle the refreshToken process:
const setup = (store) => {
axiosInstance.interceptors.request.use(
(config) => {
const token = TokenService.getLocalAccessToken();
if (token) {
// const uid = await decodeUserJWT(token);
config.headers["Authorization"] = 'Bearer ' + token;
// config.headers["userAuth"] = uid;
}
return config;
},
(error) => {
return Promise.reject(error);
}
);
const { dispatch } = store;
axiosInstance.interceptors.response.use(
(res) => {
return res;
},
async (err) => {
const originalConfig = err.config;
if (originalConfig.url !== "/auth/token/obtain/" && err.response) {
console.log("TOKEN INTERCEPTOR");
// Access Token was expired
if (err.response.status === 401 && !originalConfig._retry) {
originalConfig._retry = true;
try {
const rs = await axiosInstance.post("/auth/token/refresh/", {
refresh: TokenService.getLocalRefreshToken(),
});
const { access } = rs.data;
dispatch(refreshToken(access));
TokenService.updateLocalAccessToken(access);
return axiosInstance(originalConfig);
} catch (_error) {
return Promise.reject(_error);
}
}
}
return Promise.reject(err);
}
);
};
What happens?
When I add the line config.headers["userAuth"] = uid; the django server console starts showing up that when the react app tries to access the routes it gets a Not Authorized, and when I take that line off de code ... it works fine.
I also tried to pass the param userAuth in the axios.create and keep only the Bearer config inside the interpector code, but still no positive result, the code with the interpector code only works when I take off the userAuth line from axios.
Any ideia on why this is happening and how can I fix this?

Categories

Resources