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 .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.