Тело запроса пусто при отправке данных на сервер из Angular - PullRequest
0 голосов
/ 27 мая 2018

Я пытаюсь получить данные со стороны клиента (в Angular) на сервер nodejs.

В Angular я объявил службу.

export class AddTaskService {

  constructor(private http: HttpClient) { }
  url = 'http://localhost:3000/tasks';
  posttasks(task) {
    return this.http.post<string>(this.url, JSON.stringify({ task: task }));
  }

}

На сервере я добавил bodyparser инастроил его

index.js

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

router.js

router
    .route("/tasks")
    .post(function (req, res) {
        var taskModel = new taskSchema();
        taskModel.task = req.body.task;
        console.log(req.body);
        taskModel.save(function (err) {
            if (err) {
                res.send(err);
            }
            res.json({
                message: "nouvProj created!"
            });
        });
    });

Использование почтальона с x-www-form-urlencoded работало, но в Angular, когда II отправлял данные req.bodyпусто

Редактировать: Вот детали сети URL: Общие

Request URL: http://localhost:3000/tasks
Request Method: POST
Status Code: 200 OK
Remote Address: [::1]:3000
Referrer Policy: no-referrer-when-downgrade

Заголовки ответов

Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept
Access-Control-Allow-Methods: GET, POST, PUT ,DELETE
Access-Control-Allow-Origin: *
Connection: keep-alive
Content-Length: 31
Content-Type: application/json; charset=utf-8
Date: Sun, 27 May 2018 19:24:57 GMT
ETag: W/"1f-NlZ/5EsK7Z/S3Ze5LQN4AonQQ90"
X-Powered-By: Express

Заголовки запроса

Accept: application/json, text/plain, */*
Accept-Encoding: gzip, deflate, br
Accept-Language: fr-FR,fr;q=0.9,ar-TN;q=0.8,ar;q=0.7,en-US;q=0.6,en;q=0.5
Cache-Control: no-cache
Connection: keep-alive
Content-Length: 14
Content-Type: text/plain
DNT: 1
Host: localhost:3000
Origin: http://localhost:4200
Pragma: no-cache
Referer: http://localhost:4200/
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36

Запрос полезной нагрузки

{task: "klj"}
task
:
"klj"

Ответы [ 3 ]

0 голосов
/ 08 августа 2018

Как подсказывает @Joshua, но вам нужно просто немного изменить

const httpOptions = {
    headers: new HttpHeaders({
        'Content-Type': 'application/x-www-form-urlencoded',
    })
}
return this.http.post<string>(this.url, {task, httpOptions});

и в вашем серверном API вы должны получить данные типа

const data = req.body.task  
0 голосов
/ 18 октября 2018

createTask(task) {
  const httpOptions= {headers: new HttpHeaders({'Content-Type':'application/json})};
  const json = JSON.stringify(task);
  
  this.http.post(this.url, json, this.httpOptions);
}
0 голосов
/ 27 мая 2018

Вы можете передавать HTTP-заголовки как опции:

const httpOptions = {
    headers: new HttpHeaders({
        'Content-Type': 'application/x-www-form-urlencoded',
    })
}
return this.http.post<string>(this.url, task, httpOptions);
...