Hi I am beginner in sveltekit. I try to get post data in sveltekit here is my POST Request.
I am using axios to send post data.
const request = await axios
.post("/api/user", {
username,
email,
password,
repassword
})
.then((e) => {
console.log(e)
})
.catch((e) => {
console.error(e);
});
and this is my POST Endpoint:
// src/routes/user/+server.ts
export const POST = async({request}) => {
console.log(request)
return new Response(JSON.stringify({something: 1}))
}
this api working fine with GET methods.
Looks like the routes just don't match.
src/routes/user/+server.ts equates to just /user.
Related
So I'm making a simple CRUD app trying to familiarize myself with redux. Basically I'm transferring data from a form and sending a post request to the server to create a new blog post (more or less). Here's the code for the onSubmit:
const handleSubmit = (e) => {
e.preventDefault()
dispatch(createPost(postData));
}
Here's the action being dispatched and where the error is coming from (src/actions/posts.js):
export const createPost = (post) => async (dispatch) => {
try
{
const { data } = await api.createPost(post);
dispatch({ type: "CREATE", payload: data});
}
catch (error)
{
console.log(error.message);
}
}
This function isn't able to destructure data from the api's response, because the response is undefined. Here's the code that sends the request from src/api/index.js:
export const createPost = (newPost) => {
axios.post(url, newPost);
}
When I console.log the response from this function using .then(), it returns a 201 along with exactly what one would expect from a successful request. So the response returns 201 and the entry gets added to the DB but my action function cannot destructure the data from the response because it's undefined. What is my stupid mistake?
You aren't returning a value from the function. Try
export const createPost = (newPost) => {
return axios.post(url, newPost);
}
I'm working on an backend API but at some point I need to get user data from another API. I am trying to use Axios to make http request in order to do that. The request return the result in the browser as expected but the problem is that I can't display console log in the terminal. It doesn't show anything even though I asked the program to do so. Is there a problem probably with my code?
Here is my code :
const axios = require('axios');
const AxiosLogger = require('axios-logger');
const instance = axios.create();
module.exports = (router) => {
router.get('/profile', function(req, res) {
//random fake profile info
axios.get('https://randomuser.me/api/')
.then(response => {
console.log(response.data);
console.log(response.data);
return response.data
})
.catch(error => {
console.log(error);
});
});
};
I would suggest trying response.send to forward the axios response to your client like so:
module.exports = (router) => {
router.get('/profile', function(req, res) {
//random fake profile info
axios.get('https://randomuser.me/api/')
.then(response => {
console.log(response.data);
// Send the axios response to the client...
res.send(response.data)
})
.catch(error => {
console.log(error);
});
});
};
I am using the MERN-Stack (React, NodeJS, React, Express, + MongoDB). I want to write a get-request with Axios to call up a route in the backend. But I only want to retrieve specific data from my database. For that I want to use a query.
My URL looks something like this:
'http://localhost:5000/users?name=john'
So I only get users whose name is John.
I wrote an axios-request, which looks like this:
axios
.get("http://localhost:5000/user/getown", { params: { username: this.state.username } })
.then((response) => {
this.setState({ users: response.data });
})
.catch((error) => {
console.log(error);
});
I am not sure if I pass the query correctly.
In the backend I am using Express and Mongoose to get the date from my MongoDB. Therefore I am using this code:
router.route("/getown").get((req, res) => {
User.find({ username: req.query.username })
.then((user) => res.json(user))
.catch((error) => res.status(404).json("Error: " + error));
});
When I test the '/getown' route with Insomnia everything works correctly, so I think the mistake is in the frontend.
My endpoint will send a response like this:
res.status(400).json({"note","this email is already taken"});
With React I am using axios as follows
export const signUpUser = (email, password) => {
const headers = {
"Content-Type": "text/plain",
};
return axios
.post(
https://domain.something + "/signup",
{ email, password },
{ headers ,}
)
.then((res) => {
return res;
})
.catch((err) => {
return err;
});
};
postman can parse it as follows:
however I can not extract the JSON with react this is what displays console log shows:
By default 400 is the code for bad request, have a try to change the code to 200 or 2xx.
After some reading I learned that Axios processes express responses differently than other libraries. It treats the response as an object and only appears to take the first one (chaining did not work).
solution:
return res.json({
message: "This email is currently in use.",
status: 400,
foo: "bar",
data: "this is the data",
})
result:
I'm trying to make a POST request using axios to my firebase cloud-function on form submit in react app. But I get '500' error everytime I make a request with an html-page response This app works best with javascriot enabled.
Latest Update:
It looks like there is no issue with cloud function
code. Rather more of a react-component issue. I used Postman to send
the POST request with header prop Content-Type set to application/json
and sending body in raw format {"email": "example_email"} and got
expected response from the cloud function. But when sent the request from
react component above, I get an html file response saying the app
works best with javascript enabled
I've tried setting Content-Type to both Application/json and multipart/form-data as I suspected it to be an issue but still got no luck.
Following is my code for cloud function and react submit form:
Cloud Function
const functions = require('firebase-functions');
const cors = require('cors')({ origin: true })
const runThisFunc1 = require(./libs/runThisFunc1);
const runThisFunc2 = require(./libs/runThisFunc2);
exports.wizardFunc = functions.https.onRequest((request, response) => {
cors(request, response, () => {
let email = request.body.email;
try {
return runThisFunc1(email)
.then(data => {
console.log("Word Done by 1!");
return runThisFunc2(data);
})
.then(res => {
console.log("Word Done by 2!");
return response.status(200).send("Success");
})
.catch(err => {
console.error("Error: ", err.code);
return response.status(500).end();
});
}catch(err) {
return response.status(400).end();
}
});
});
React-Form-Component Snippet
import axios from 'axios'
...
handleSubmit = e => {
e.preventDefault()
const { email } = this.state
axios({
method: 'post',
url: `${process.env.REACT_APP_CLOUD_FUNCTION_ENDPOINT}`,
data: { email: email },
config: {
headers: {
'Content-Type': 'multipart/form-data'
}
}
})
.then(res => {
//do something with reponse here
})
.catch(error => {
console.error(error)
})
}
...
Is there something wrong I am doing in the code or the request config is wrong?