S
S
Sasha Yashchuk2019-07-02 18:17:49
Angular
Sasha Yashchuk, 2019-07-02 18:17:49

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:
5d1b73e40180a990808823.jpeg
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});
    }

I subscribe to the event in the component:
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()
  }

here is the code on the server:
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)}};
    }

Tell me what I'm doing wrong, or what needs to be done? I understand that the problem is related to cross-domain requests, I thought that it was a matter of headers, so I added them wherever possible, reviewed a bunch of sites, but did not find a specific solution ... I also thought that the problem might be related to the format of the data being sent, because postman handles the request correctly.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Anton Shvets, 2019-07-02
@Alex_bliznec

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
  }
}

run as
well, and the server should accept all apish requests as /api/whatever there

I
Ivan Shumov, 2019-07-02
@inoise

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

L
Ler Den, 2019-07-02
@givemoneybiatch

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 question

Ask a Question

731 491 924 answers to any question