Discord.js v14 DiscordAPIError[40060]: Interaction has already been acknowledged - discord

My discord command does not work due to the error DiscordAPIError[40060]
I've tried seeing what caused it but couldn't heres my code:
if (!interaction.isChatInputCommand()) return;
if (interaction.commandName === 'help') {
await interaction.deferReply();
await wait(800);
await interaction.editReply({ embeds: [helpEmbed] });
}
});
client.on(Events.InteractionCreate, async interaction => {
if (!interaction.isChatInputCommand()) return;
if (interaction.commandName === 'wombat') {
await interaction.deferReply();
await wait(800);
await interaction.editReply({ embeds: [embed] });
}
});````

Related

Request working correctly on Postman but gives a 404 error when I process it via React App

I have been trying to working with Github Gists API, specifically the "Star a Gist"functionality but I am noticing a strange behavior when I send a request via my React app.
Here's the code for the request:
const starNote = async (noteId, token) => {
const config = {
headers: {
Authorization: `Bearer ${token}`,
"Content-Length": "0",
},
}
try {
const response = await axios.put(`${API_URL}/${noteId}/star`, config, {
noteId: noteId,
})
console.log("request sent")
if (response.status === 204) {
console.log("working", response)
return true
}
} catch (error) {
if (error.response.status === 404) {
console.log(error)
}
}
}
And here's the code for the slice function:
export const starNote = createAsyncThunk(
"notes/starNote",
async (noteId, thunkAPI) => {
try {
const token = thunkAPI.getState().auth.user.accessToken
return await notesService.starNote(noteId, token)
} catch (error) {
const message =
(error.response &&
error.response.data &&
error.response.data.message) ||
error.message ||
error.toString()
return thunkAPI.rejectWithValue(message)
}
}
)
The action gets triggered correctly but the request doesn't go through the:
console.log("request sent")
part and goes straight to the error. If you send a GET request, it gives a 404 error if you haven't starred a gist. But for the PUT request, why does it go straight to the error and not send the request. If i try the same with Postman it works correctly and returns a
response.status: 204
What am I doing wrong here?
Okay so what I did was insert this in the PUT request:
{ noteId: noteId }
And it worked.
Here's the complete code of the call:
const starNote = async (noteId, token) => {
const config = {
headers: {
Authorization: `Bearer ${token}`,
"Content-Length": "0",
},
}
try {
const response = await axios.put(
`${API_URL}/${noteId}/star`,
{ noteId: noteId },
config
)
console.log("request sent")
if (response.status === 204) {
console.log("working", response)
return true
}
} catch (error) {
if (error.response.status === 404) {
console.log(error)
}
}
}
I am still not sure why it's necessary but this is what it needed.

When checking the cookie I get an undefined

everyone. I'm trying to set a cookie using epress for 24 hours. Setting also works (developer tools). For example, if I now go into standby mode and return to the application, click on something that triggers a request 'load all articles of a user', then the token is undefinded and the cookie is said to be not set. How can I fix this?
In Debugger I see the access_token cookie. So this is there, but when I check 'verifyToken.js' I get an undefined.
ladeAlleArtikelEinesUsers:
const ladeAlleArtikelEinesUsers = async (artikelId) => {
try {
await axiosInstance
.post(`/artikel/finde/${artikelId}`, { withCredentials: true })
.then(async (res) => {
//TOKEN is undefined here
if (res.data.error) {
signOut(auth)
.then(() => {
dispatch(logout());
navigate("/Login");
})
.catch((error) => {
console.log(error);
});
} else {
setArtikelEinesUsers(res.data);
setOeffneArtikelEinesUsersDialog(true);
}
});
} catch (error) {
console.log(error);
}
};
verifyToken.js
export const verifyToken = (req, res, next) => {
const token = req.cookies.access_token;
console.log("TOKEN: " + token ); //UNDEFINED
if (!token) {
return res.status(200).send({
error: true,
msg: "Authentication Failed.",
});
}
jwt.verify(token, process.env.JWT, (err, user) => {
if (err) {
return res.status(200).send({
error: true,
msg: "Authentication Failed.",
});
}
req.user = user;
next();
});
};
route
router.post("/finde/:id", verifyToken, EinArtikel);

Token undefined in put and patch request. MERN stack application

Working with a mern application. I am passing token in authorization header. The issue is whenever I use put or patch method from frontend, token is undefined. Get, Post, Delete requests are working fine. Api is working fine with postman too.
frontend action ->
export const approveClient = (id) => async (dispatch) => {
try {
const config = {
headers: {
Authorization: `${localStorage.getItem("token")}`,
},
};
dispatch({ type: adminConstants.APPROVECLIENT_REQUEST });
const res = await axios.put(`/admin/approveClient/${id}`, config);
dispatch({
type: adminConstants.APPROVECLIENT_SUCCESS,
payload: res.data,
});
} catch (error) {
dispatch({
type: adminConstants.APPROVECLIENT_FAIL,
payload: error.response.data,
});
}
};
Backend middleware function ->
const isAuthenticated = async (req, res, next) => {
try {
const token = req.headers.authorization;
if (!token) {
return res.status(401).json({ success: false, message: "Not logged in" });
}
const decoded = jwt.verify(token, process.env.JWT_SECRET);
const user = await User.findById(decoded._id);
const client = await Client.findById(decoded._id);
const admin = await Admin.findById(decoded._id);
if (user) {
req.user = user;
}
if (client) {
req.user = client;
}
if (admin) {
req.user = admin;
}
next();
} catch (error) {
res.status(500).json({ success: false, message: error.message });
}
};

How to send error messages from express to react/redux

I have a MERN app using redux. My actions look like this:
export const logIn = (logInData) => async (dispatch) => {
try {
const { data } = await api.logIn(logInData);
localStorage.setItem('auth', JSON.stringify(data))
dispatch({
type: LOG_IN,
payload: data
});
} catch (error) {
dispatch({
type: ADD_FLASH_MESSAGE,
payload: error
})
}
}
And my server looks like this
export const logIn = async (req, res) => {
const logInParams = req.body;
const user = await User.findOne({ email: logInParams.email });
if (!user) {
console.log("USER NOT FOUND");
res.status(400).json({
message: "Invalid credentials."
});
}
const passwordMatches = await bcrypt.compare(logInParams.password, user.password);
if (!passwordMatches) {
console.log("WRONG PASSWORD")
return res.status(400).json({
message: "Invalid credentials."
})
}
// Sign in user with jwt
const payload = {
user: {
id: user.id
}
}
jwt.sign(payload, config.get('jwtSecret'), (error, token) => {
if (error) throw error;
console.log('Successfully logged in');
return res.status(200).json({
token: token,
user: user,
loggedIn: true
});
})
}
I'm not able to access my error messages in my actions. I just get error messages like so
POST http://localhost:5000/auth/login 400 (Bad Request)
And my console.log looks like this:
Error: Request failed with status code 400
at createError (createError.js:16)
at settle (settle.js:17)
at XMLHttpRequest.handleLoad (xhr.js:62)
How do I access my custom error messages from my server?
try to get the status as error.status and custom message as error.data.message
your custom error message contain in error.response.data
try change this in your action:
export const logIn = (logInData) => async (dispatch) => {
try {
const { data } = await api.logIn(logInData);
localStorage.setItem('auth', JSON.stringify(data))
dispatch({
type: LOG_IN,
payload: data
});
}
catch (error) {
dispatch({
type: ADD_FLASH_MESSAGE,
payload: **error.response.data**
})
}
}

Sending response of multiple api calls from action to view file in react js with redux

I am beginner to React JS and Redux and have got stuck in a problem. I have to call a login api and if that return success I need to call another api using axios to get user details. Following is my function in action doing it:
export const login = (username, password) => (dispatch) => {
return AuthServicee.login(username, password).then(
(data) => {
if(data.success) {
userService.getUserDetails(username).then((data) => {
localStorage.setItem("user", JSON.stringify(data.data));
dispatch({
type: LOGIN_SUCCESS,
payload: { user: data },
});
return Promise.resolve();
},(error) => {
const message =
(error.response &&
error.response.data &&
error.response.data.message) ||
error.message ||
error.toString();
dispatch({
type: LOGIN_FAIL,
});
dispatch({
type: SET_MESSAGE,
payload: message,
});
return Promise.reject();
}).catch(err => {
dispatch({
type: LOGIN_FAIL,
});
});;
} else {
dispatch({
type: LOGIN_FAIL,
});
dispatch({
type: SET_MESSAGE,
payload: data.error,
});
}
},
(error) => {
const message =
(error.response &&
error.response.data &&
error.response.data.message) ||
error.message ||
error.toString();
dispatch({
type: LOGIN_FAIL,
});
dispatch({
type: SET_MESSAGE,
payload: message,
});
return Promise.reject();
}
);
};
I am calling the above function from my login page as following:
const handleLogin = (e) => {
e.preventDefault();
setLoading(true);
form.current.validateAll();
if (checkBtn.current.context._errors.length === 0) {
dispatch(login(username, password))
.then(() => {
setLoading(false);
if (props !=null && props.isAuthenticated) {
props.history.push("/home");
}
})
.catch(() => {
setLoading(false);
});
} else {
setLoading(false);
}
};
Now since I have return with the first API call, it returns data as soon as the first API provides a response and does not wait for the second call to finish. It should wait till both API calls are finished and then return the result to Login.js.
Can someone please help me here?
Working Solution as per cb dev answer
const login = async (username, password) => {
try {
const loginRes = await loginUser(username, password);
if (loginRes.data != null && loginRes.data.success) {
localStorage.setItem("access_token", loginRes.data.data);
const getUserRes = await getUserDetail(loginRes.data.data, username);
localStorage.setItem("user", JSON.stringify(getUserRes.data));
return getUserRes.data;
} else {
return loginRes.data;
}
}catch (err) {
console.log("Something went wrong with the login process...");
console.log(`I can log the error here: ${err}`);
}
}
function loginUser(username, password) {
return new Promise((resolve, reject) => {
const response = axios
.post(API_URL + "users/authenticate", {
username,
password,
});
resolve(response);
});
}
function getUserDetail(access_token, username) {
return new Promise((resolve, reject) => {
console.log(`Login_step2: I've got ${access_token}...`);
var url = apiConfig.API_BASE_URL + "users?username="+username;
resolve (axios.get(url, { headers: authHeader() }));
});
}
You should be using async-await syntax. It will make your code much nicer to read and will be a lot easier to control the behavior you're intending.
https://javascript.info/async-await
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await
Something like this:
CodeSandbox Link
import React from "react";
import "./styles.css";
function mockLogin_step1() {
return new Promise((resolve, reject) => {
setTimeout(() => resolve("Login_step1 success"), 1000);
});
}
function mockLogin_step2(something) {
return new Promise((resolve, reject) => {
console.log(`Login_step2: I've got ${something}...`);
setTimeout(() => resolve("Login_step2 success"), 1000);
});
}
function App() {
async function doLogin() {
try {
console.log("Calling async API login STEP 1");
const step1Result = await mockLogin_step1();
console.log(step1Result);
console.log("Calling async API login STEP 2");
const step2Result = await mockLogin_step2("something from step1");
console.log(step2Result);
console.log("I can dispatch something here...");
} catch (err) {
console.log("Something went wrong with the login process...");
console.log("An error probably happened on step1 or step2...");
console.log(`I can log the error here: ${err}`);
console.log("I can dispatch something here...");
}
}
return <button onClick={doLogin}>Login</button>;
}
export default App;
The resulting log:

Resources