sending data from angular to node api - node.js

i am beginner so i apologize if my question isn't relevant or easy to fix, but i couldn,t fix my issue yet, for 4 days.
I am working on an api, which will receive data from angular form, then store it with sequelize on a mariadb table.
When i submit my form, which would through the url, post it in the table through the api, i can see that the req.body is defined, and it reachs the api, but yet i have and error in my angular http post which is thrown(error 500).
With postman, i see that my url isn t reachable, i can't figure out so if my error comes from the post angular, or the backend with my model, even if error 500 is for back end.
I tried to redefine my sequelize model, parse and stringify the object i send, try others url...but nothing works.
So here is my function called when the form is submitted,the function formatrequestschedulest return the object i want to post.
onSubmitScheduled(){
let OndemandScheduledRequest = this.formatRequestScheduled(this.selectedHotel, this.selectedCheckInDate, this.selectedCheckOutDate, this.selectedNumber, this.selectedCurrency, this.selectedReportName, this.selectedUser, this.selectedEmail, this.selectedFormat);
console.log(OndemandScheduledRequest);
this.saveScheduledRequest(OndemandScheduledRequest);
return this.openDialog();
}
saveScheduledRequest(onDemandScheduledRequest: OnDemandScheduledRequest){
this.http.post('/api/ScheduledReport', JSON.stringify(onDemandScheduledRequest), {headers: {'Content-Type': 'application/json'}})
.subscribe(res=>{ console.log(res
)
console.log('ok')},
(err) =>
console.log('an error'))
/*console.log(err))*/
}
And here is my api:
var request= require('../controller/ondemandscheduledrequests');
var router = express.Router();
router.get('/getreport',request.create);
router.post('/ScheduledReport',request.create);
I can provide also the error i get, but i don't know if i can join a picture to the question.
I just want to have my form data store to my table, but i get an error 500 instead.
this is the error i get

Use pipe like below and try once
this.http.post('/ScheduledReport', JSON.stringify(onDemandScheduledRequest).pipe().subscribe(val => {
console.log(val, "service");
, {headers: {'Content-Type': 'application/json'}})}

Related

How do I use the the post method with fetch and koa?

This is a function on my front-end that makes the request.
function postNewUser(){
fetch(`http://12.0.0.1:8080/users/test`, {
method: 'POST',
body: {nome: name, email: "test#test.com.br", idade: 20}
})
}
This is my back-end code to receive the request.
router.post('/users/:id', koaBody(), ctx => {
ctx.set('Access-Control-Allow-Origin', '*');
users.push(ctx.request.body)
ctx.status = 201
ctx.body = ctx.params
console.log(users)
})
For some unknown reason I receive nothing. Not even a single error message. The "console.log()" on the back-end is also not triggered, so my theory is that the problem is on the front-end.
Edit
As sugested by gnososphere, I tested with Postman, and it worked. So now i know the problem must be on the fron-end code.
You can try your backend functionality with Postman. It's a great service for testing.
the request would look something like this
If the problem is on the frontend, double check your fetch method by posting to a website that will return data and logging that in your app.

Confusion about data flow on HTTP requests - what part is HTTP and what is JSON?

I'm going to use the following code as an example to frame my question. It's basically just the code required to pull a list of to dos from an SQLite3 database:
So, there's an axios request in the front end:
useEffect(() => {
axios.get('http://localhost:3001/todo', {})
.then(res => {
setTodoList(res.data)
})
.catch(err => {
console.log(err)
})
}, [])
...which links to the following function in the back end:
server.get('/todo', (req,res) => {
// res.json(testData)
const todos = db('todos') //this is shorthand for 'return everything from the table 'todos''
.then(todos => {
return res.json(todos)
})
})
..the data from this GET request is then rendered within a react component, as a list of text.
I'm just confused about the flow of data - when is it HTTP, when is it JSON, what form does the data come out of the database as, and how is it that these different protocol/languages can talk to each other?
I get the overall principle of a GET request and async functions, I just don't get what's going on under the hood. Thanks!
That's a lot of questions about basic issues. But here are some answers. Firstly, you can simplify the server function as:
server.get('/todo', (req, res) => {
db('todos').then(todos => res.json(todos));
});
The data from the db is a Javascript array by the time you are dealing with it in Express. res.json converts it into JSON, which is of course, just a string.
Express creates an HTTP response, which consists of some headers (key value pairs such as Content-Length: and so on) followed by a body, which in your case is just a JSON blob, a string. That response object is sent over the network via HTTP.
The browser receives the response and axios is kind enough to handle the grunt work of reading the headers and turning your JSON back into a Javascript array/object which can then be handled inside React.
The part I can't answer is "how is it that these different protocol/languages can talk to each other", because that is very complex and the question is not well defined. There are many network layers involved.

Postman Mongoose response empty array

I am working on an app that responses are set like
req.data = data
I created a new endpoint, and if I console.log the data, I can see that mongoose is retriving the data. But postman is showing an empty array in the response
Also if I add
res.json(data)
Postman will show the json, but I don't want to change the app style
Probably I forgot to set something
Usually i use express to make API responses as the following :
app.get('/',(req,res)=>{
// some code goes here that will return DATA
res.status(200).json(DATA) // And This line will return a JSON file to postman
})
NOTE : use req.something to handle your incoming data, res.something to make a response to the client.

Why is res undefined in some cases?

I'm working on a ReactJS project and I'm using Axios to connect to my NodeJS backend using express and a MongoDB Database.
I have a button in my render function that when clicked calls the following function:
getInfo() {
Axios.get('http://localhost:9000/getMyData')
.then(res => console.log(res));
}
This works fine, it connects, queries my database and I can see the results in my console.
BUT
If I try to set the state with this result, it is undefined.
For example:
getInfo() {
Axios.get('http://localhost:9000/getMyData')
.then(res => this.setState({data: res})); // or res.data based on the way I want to save it
}
I get a 304 response instead of a 200 response, and React says that res is undefined.
I do not understand what is going on here, why can I console log the response, but I can't store it.
Can someone please explain to me what I am doing wrong, and how I can store the data?
Thank you.

Is there any difference between using request.body or request.params in node.js?

I am wondering if there is any preference in using request.body or request.params in node.js when sending data from client to server?
You can fit more (diverse) data in the body than in the url. You can pass any string (special characters) in the body, while encoding them in the url would get you vulnerable to status 414 (Request-URI Too Long). And it's a lot easier to use the body when passing arrays and complex objects :)
I would say that a best practice would be that you should use params when doing a get, but use body for post, put and patch.
a sample get
app.get "/api/items/:id", (req, res) ->
itemController.getItem req.params.id, (item, error) =>
if !error
res.send 'item': item
else
res.send 'error: error
a sample post
app.post "/api/items", (req, res) ->
itemController.saveItem req.body, (item, error) =>
if !error
res.send 'item': item
else
res.send 'error: error
You would add validation on as well, but this has been how I have been writing all of my endpoints.
It's been over 4 years since this question was asked, however, I would still chime in to make sure somebody else stumbling upon this post has more information to understand this concept better.
req.body and req.params server two different purposes.
you would use req.body when you need to send data to a server (to store it or something), like in a "POST" request to a server. For instance, check out the following:
You are doing a "POST" request to mongodb to save a blog post. In this scenario, you would want to get the data coming in the body of the request and send it to the db. Here you would use req.body
app.post("/blog", function(req, res){
var data = req.body.blog;
.... // code to send data to the db
....
});
req.params is used when you want to extract a "param" from the url. let's say you want to extract an "id" which is part of the url. For instance "id" is the number in the following url after questions
stackoverflow.com/questions/18187424/
app.get("/xyz/questions/:id", function(req, res){
var useId = req.params.id;
...
...
});
Hope, it helps.
Thanks,
Kartik

Resources