I want to use javascript fetch to post data to Node.js backend. I use fetch on the javascript side in angular 2 functions.
In my front end I have button to save data to array:
<input #data /><button (click)="addGoal(data.value)">Add</button>
<ul><li *ngFor="let goal of goals">{{goal}}</li></ul>
<br/><button (click)="saveData()">Save</button>
Angular 2 side i add data into array goals and call angular 2 function addGoal from the front end:
export class AppComponent {
title = 'Goals';
goals = [];
addGoal(goal:string) {
this.goals.push(goal);
}
saveData() {
fetch("http://localhost:3000/", {
method: "POST",
mode:"no-cors",
body: {goals: this.goals},
});
}
}
I want to get data to backend to later save it to the database.
Node.js side:
var data = {};
app.post('/',function (req,res) {
data = req.body;
})
app.get('/', function (req, res) {
res.send(data);
})
However, this is not a correct solution. Can you help me?
edit: Body.fetch functions(https://developer.mozilla.org/en-US/docs/Web/API/Body) not seem to work.
In case you are using express, you need to use the body-parser middleware. If you are dealing with html5 FormData/multiplart formdata, you need multer.
Related
Good day,
I've been trying to learn a bit of angular and nodejs. I found a tutorial on a realtime chat app and made some few adjustment to some function of the code. But the one aspect that I cannot seem to get right is the ability for the user to post to a feed. The login process works, the user is already logged in but the user can't post. I would also like to be able to get all they data i insert from all the user to show up like a normal feedview will. Please assist.
Here are my files:
FROM MY CONTROLLER HERE IS THE CODE WHEN THE BUTTON IS PRESSED
$scope.postDatatoDd = () => {
appService.httpCall({
url: '/posts',
params: {
'posts': $scope.data.info,
'from_user_id': $scope.data.username
}
})
.then((response) => {
// $scope.$apply();
})
.catch((error) => {
alert(error.message);
});
}
and here is my route file:
this.app.post('/posts', async(request,response) => {
const reqResponse = {}
const data = {
posts : request.body.postDatatoDd,
from_user_id: request.body.username
};
if (data.posts === ''){
reqResponse.error = true;
reqResponse.message = `error, input`;
response.status(412).json(reqResponse);
} else {
const result = await helper.insertFeed(data);
if (result === null) {
reqResponse.error = true;
reqResponse.message = `they was an error.`;
response.status(417).json(reqResponse);
} else {
reqResponse.error = false;
reqResponse.userId = result.insertId;
reqResponse.message = `posted succesfully`;
response.status(200).json(reqResponse);
}
}});
and in my helper file there is this function to insert data:
async insertFeed(params){
try {
return await this.db.query(
`INSERT INTO posts (from_user_id,posts) values (?,?)`,
[params.from_user_id,params.postDatatoDd]
);
} catch (error) {
console.warn(error);
return null;
}
}
On the client side here is the button with :
<label for="postDatatoDd">Post</label>
<input type="text" id="postDatatoDd"
ng-model="data.postDatatoDd"
class="feed form-control"
placeholder="post your data here?"
/>
<button ng-click="postDatatoDd()" class="btn btn-primary">Post</button>
</div>
--- EDIT 1---
Data is being inserted now, but it is receiving the values as (NULL, NULL).
--- EDIT 2 ---
After closely looking at the code and fixing some naming variables the code works fine, the data is being inserted in mysql as it should.
Other than a lot of typos when it comes to the variables reference. The code seem to be fine.
Assuming that you using appservice class somewhere in your code and its functioned, then everything else will work.
You are getting the (NULL, NULL) because you are parsing parameters that are not being properly parsed out to your helper file, please close attention to that.
appService
.httpCall({
url: "/posts",
params: {
posts: $scope.data.postbuzz,
from_user_id: $scope.data.username,
},
})
.then((response) => {
$scope.$apply();
})
.catch((error) => {
alert(error.message);
});
make sure that the data that you calling from this above function is similar to $scope parameter you passing in your route file that your requesting:
const data = {
posts : request.body.posts,
from_user_id: request.body.from_user_id}
and in your database helper class you running:
`INSERT INTO posts (from_user_id,post) values (?,?)`,
[params.from_user_id,params.posts]
Hope this was helpful
You seem to have an understand already. your question may help a lot more people in the future.
params should be as following, since the data object has properties from_user_id and posts
`INSERT INTO posts (from_user_id,posts) values (?, ?)`,
[params.from_user_id,params.posts]
Might be useful https://www.w3schools.com/nodejs/nodejs_mysql_insert.asp
--- EDIT 2 ---
After closely looking at the code and fixing some naming variables the code works fine, the data is being inserted in mysql as it should.
If you are new to Angular you can use the code as reference.
I am trying to create a API using nodejs and access it using GET method by sending parameters using Angular 5 GET method. When I am testing my API using Postman, it works fine, but sending the GET request from Angular is not giving me the result. My node js router for receiving multiple parameters code is as follow:
router.get('/:min&:max',(req,res,next)=> {
Image.find({hue: {$gt:req.params.min,$lt:req.params.max}})
.select('name url hue')
.exec()
.then(docs => {
const response={
images: docs.map(doc=> {
return {
name: doc.name,
url: doc.url,
hue: doc.hue,
_id: doc._id,
}
})
}
res.status(200).json(docs);
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
});
});
})
My angular GET method goes like this :
getSearchedImages(min, max) {
let params = {
'min': String(min),
'max': String(max)
}
this.http.get('http://localhost:3000/', { params: params})
.subscribe(val=> console.log(val))
}
Is there any problem in Angular part or is my code in Node is to be adjusted
Use POST if you want to pass parameters in request body. Otherwise, if you like GET, pass parameters in URL.
HTTP itself doesnt restrict this, but some front-end implementations do
I am trying to use the Fetch API with my Rails application. I can pass parameters to the controller as part of a query string, but still can't figure out how to pass JSON data or where to find it in the controller. A sample call looks like the below. Where can I access my test data on in the controller? Happy Sunday :)
export const fetchControllerData = () => {
return fetch('api/users',), {
body: { "test": "test" }
})
.then(res => res.json());
};
I'm in the process of working out my own issues with fetch and Rails. But I'll take a stab at this.
I expect that fetch is using GET as the default method - which won't use the body at all. You will likely need to set the method to be POST to get the body through. Further to that you might need to set the Content-Type header (to application/json) in order to send the data through as JSON.
May be u need to send params in this way for get request and use this link for https://github.com/axios/axios
export const fetchControllerData = () => {
params = { body: { "test": "test" } }
return HTTP.get('api/users', params)
.then((response) => {
if (response.success) {
// do something here
} else {
// handle error condtion here
}
});
}
With my node.js app, I'm getting my JSON data from a spreadsheet API.
It basically returns JSON of the following.
{
"status":200,
"success":true,
"result":[
{
"Dribbble":"a",
"Behance":"",
"Blog":"http://blog.invisionapp.com/reimagine-web-design-process/",
"Youtube":"",
"Vimeo":""
},
{
"Dribbble":"",
"Behance":"",
"Blog":"http://creative.mailchimp.com/paint-drips/?_ga=1.32574201.612462484.1431430487",
"Youtube":"",
"Vimeo":""
}
]
}
It's just a dummy data for now but one thing for certain is that, I need to process values (blog URLs) under Blog differently. With the blog url, I need to get Open Graph data so I'm using a module called open-graph-scraper
With data.js I'm getting the whole JSON and it's available in route index.js as data Then I'm processing this data by checking Blog column. If it's a match, I loop the values (blog URLs) through open-graph-scraper module.
This will give me open graph data of each blog url like the following example JSON.
{
data:
{ success: 'true',
ogImage: 'http://davidwalsh.name/wp-content/themes/punky/images/logo.png',
ogTitle: 'David Walsh - JavaScript, HTML5 Consultant',
ogUrl: 'http://davidwalsh.name/',
ogSiteName: 'David Walsh Blog',
ogDescription: 'David Walsh Blog features tutorials about MooTools, jQuery, Dojo, JavaScript, PHP, CSS, HTML5, MySQL, and more!' },
success: true
}
So my goal is to pass this blog JSON as a separate data from the main JSON and put it in the render as a separate object so it's available in view as two separate JSON. But I'm not sure if my approach with getBlogData is correct.
I'm not even sure if processing data like this is a good thing to do in a router file. I would appreciate some directions.
index.js
var ogs = require('open-graph-scraper');
var data = require('../lib/data.js');
data( function(data) {
var getBlogData = function (callback) {
var blogURL = [];
if (data.length > 0) {
var columnsIn = data[0];
for(var key in columnsIn) {
if (key === 'Blog') {
for(var i = 0; i < data.length; i++) {
blogURL += data[i][key];
}
}
}
};
ogs({
url: blogURL
}, function(er, res) {
console.log(er, res);
callback(res);
});
}
getBlogData( function (blogData) {
//I want to make this blogData available in render below
but don't know how
});
router.get('/', function(req, res, next) {
res.render('index', {
title: 'Express',
data: data
});
});
});
data.js (my module that gets JSON data)
module.exports = function(callback) {
var request = require("request")
var url = "http://sheetsu.com/apis/94dc0db4"
request({
url: url,
json: true
}, function (error, response, body) {
if (!error && response.statusCode === 200) {
var results = body["result"];
callback(results)
}
})
}
The problem you'll have is that if you do getBlogData asynchronously (and you should, you don't want the client waiting around for all that data to return), by the time you get the data res.render will have already been called. As you can't call res.render again, you have 2 options that come to mind:
You could query for individual blog data from the client. This will result in more back-and-forth between client and server but is a good strategy if you have a lot of entries in your initial data but only want to display a small number.
You could use websockets to send the data to the client as you retrieve it. Look up something like express.io for an easy way to do this.
I have a post request I am doing like so:
var addProject = function (project, id) {
return $.ajax(projectUrl, {
type: "POST",
data: { project: project, id: id }
});
};
This is all fine, and it send up my project object (in JSON) with no problem. What i want to do is this request but also add in a key (that does not belong in the project object) that I can pass to the server controller. Any idea if I can do this, or what is a good way to do this. I really don't want to have to go back and change my object models to account for a key that I will only need every once in awhile.
This is an ASP.NET MVC4 project, and it is going back to a web api controller if that matters.
EDIT: here is my server side stuff
public HttpResponseMessage PostNew(Project project, int id)
{
//TODO grab the client to add the project to
Uow.Projects.Add(project);
Uow.Commit();
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, project);
//response.Headers.Location = new Uri(Url.Link("ApiControllerAction", new { id = client.ID }));
return response;
}
Maybe I am not being clear enough. I want to pass in the project object, and then just an int variable. Passing project alone works, but if I try to pass the int it gives me a 400 error
var addProject = function (project) {
return
$.ajax(projectUrl, {
type: "POST",
data: {data1 : 'Object',data2: 'variable'}
});
};
You have just to send 2 data params., object and var..
Easiest way to pass a complex object is to JSON-encode it:
var addProject = function (project) {
return $.ajax(projectUrl, {
type: "POST",
contentType: 'application/json',
data: JSON.stringify(project)
});
};
To decode this on the server side, you will need a JSON decoder of some kind. I'm sure C# has some available.