Answer the question
In order to leave comments, you need to log in
How to send Angular form data via POST request?
For educational purposes, I am writing an application in Angular, which should receive / send data from a form to the server. The node.js server is running on local port 8888, Angular is on 4200. The get request is fine and returns me an array of objects from the database. But when I send a POST request to add, I get the following error:
Here is the code on the client:
@Injectable()
export class HttpService {
constructor(private http: HttpClient) {}
getAuthors() {
return this.http.get('http://localhost:8888/authors');
}
postAuthor(author: Author) {
const body = {name: author.name, id: author.id};
const headers: HttpHeaders = new HttpHeaders({'Content-Type':'application/x-www-form-encoded'});
// console.log(`this is body`);
// console.log(body)
return this.http.post('http://localhost:8888/author', body, {headers});
}
addAuthor() {
// console.log(this.form);
const recievedAuthor: Author = {name: this.form.value.name, id: +this.form.value.id};
// console.log(recievedAuthor);
this.httpService.postAuthor(recievedAuthor).subscribe()
}
createAuthor: async (ctx) => {
if (ctx.request.body.name === '' || ctx.request.body.name === undefined
&& ctx.request.body.id === '' || ctx.request.body.id === undefined) {
ctx.body = {"validation error": "Все поля должны быть заполнены"};
return;
}
try {
const author = await Author.create({
id: ctx.request.body.id,
name: ctx.request.body.name
});
ctx.body = `author ${author} created`;
} catch {(err) => {console.log(err)}};
}
Answer the question
In order to leave comments, you need to log in
You don't need to add cors on the back without need. Set up proxy https://github.com/angular/angular-cli/blob/master...
specifically for you - create proxy.conf.json file with content
{
"/api": {
"target": "http://localhost:8888",
"secure": false
}
}
For the 100500th time, it googles in 5 minutes. The browser blocks calls to another domain from js, so you need to give the Access-Control-Allow-Origin header with the desired domain on the server
try 'Content-Type' in the list of headers
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization, Refresh");
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,PATCH,DELETE');
res.header("Access-Control-Allow-Credentials", "true");
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question