【问题标题】:Delete request not working删除请求不起作用
【发布时间】:2018-11-26 16:43:23
【问题描述】:

我正在尝试在我的项目中提出“删除请求”,但没有成功...

向我返回此消息:

""错误 HttpErrorResponse {headers: HttpHeaders, status: 200, statusText: "OK", url: "http://localhost:8080/produtos", ok: false, ...}""

我在 service.ts 上的方法是这样的:

 deleteProduct (productId: number): Observable<Product> {
      const url = `${this.produtosUrl}`;
      return this.http.delete<Product>(url, httpOptions).pipe(
          map((response: Response) => response.json())
 )

}

我的组件.ts:

  delete(productId: number): void {
  this.products = this.products.filter(Product => Product.id !== productId);

  this.produtoService.deleteProduct(productId).subscribe();
}

我在 node.js 上的方法:

app.delete('/produtos', function (req, res) {
    console.log(req.body);
    mc.query('DELETE FROM `produtos` WHERE `id`=?', [req.body.id], function 
(error, results, fields) {
    if (error) throw error;
    res.end('Record has been deleted!');
  });
 });

当然还有html按钮:

<tbody>
   <tr *ngFor="let product of products">
      <th scope="row">{{product.id}}</th>
      <td>{{product.nome}}</td>
      <td>{{product.price}}</td>
      <td>{{product.url}}</td>
      <td> <button class="btn-primary delete" title="delete product"
        (click)="delete(product.id)">
        Delete
      </button></td>
    </tr>
  </tbody>

很高兴你能帮助我。

@Edit: github 上的项目 =

https://github.com/Mauricio-vieira/Front-End-Project

https://github.com/Mauricio-vieira/Back-end-Project

【问题讨论】:

  • 能否请您发布完整的错误代码?
  • 错误就是这个(从 f12 获取) ERROR HttpErrorResponse {headers: HttpHeaders, status: 200, statusText: "OK", url: "localhost:8080/produtos", ok: false, …}
  • 你能在开发者工具中检查你的网络标签吗,你可能有 403 错误?这可能是由于 CORS,请求中不允许使用大多数 DELETE 方法。
  • 根据您的错误/代码,很难确定确切的问题是什么,要么提供更多信息,要么在某些 plunker 或 stackblitz 上重现相同的错误
  • reqURL:localhost:8080/produtos 请求方法:DELETE 状态代码:200 OK 远程地址:[::1]:8080 推荐人策略:no-referrer-when-downgrade 访问控制允许来源: * 连接:keep-alive 内容长度:24 日期:2018 年 6 月 17 日星期日 18:26:45 GMT X-Powered-By: Express Accept: application/json, text/plain, / Accept - 编码:gzip的,放气,BR接受语言:PT-BR,PT; q = 0.9,的en-US; q = 0.8,连接; q = 0.7授权:承载eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiI1YjI1ODAwMGE5ZWNmMTNiMTRjZGIyNzYiLCJpYXQiOjE1MjkyNTc0Mjd9.6Wsv7MXLO9aQ1F1VR0WkXUhSuRn68c4O67dQCLualmc 跨度>

标签: javascript node.js angular typescript


【解决方案1】:

在您的 Angular 代码中,您正在尝试解析响应:

map((response: Response) => response.json())

如果响应为空,这将失败,因为那不是有效的 JSON。删除此行,或更改您的后端以返回一些有效的 JSON

如果您使用的是 HttpClient,默认情况下会尝试将其解析为 JSON,因此删除该行不会修复它。除了删除该行之外,您还需要在 httpOptions 中将 responseType 设置为 text

const httpOptions = {
  headers: new HttpHeaders({ 'Content-Type': 'application/json' }),
  responseType: 'text' as 'text'
}

(请注意,我们必须根据this issue 显式键入responseType。另外请注意,无需更改Content-Type 标头,因为您仍在发送JSON,只是没有返回JSON。)

【讨论】:

  • @MauricioRenan 你在 Angular 中使用 HttpHttpClient 吗?
  • 是的,所有这些进口:
  • 从'@angular/core'导入{可注入};从'./product'导入{产品};从 'rxjs' 导入 { Observable, of };从“@angular/common/http”导入 { HttpClient, HttpHeaders };从 'rxjs/operators' 导入 {tap} const httpOptions = { headers: new HttpHeaders({'Content-Type': 'application/json '}) }
  • @MauricioRenan 刚刚更新了答案,请试一试
  • 我不明白...如何更改对文本的响应?
【解决方案2】:

对于删除请求,您需要在标头中允许删除请求。 使用 res.header("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE");

或者添加这个中间件

app.use((req,res,next)=>
    res.header("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE");
    next()
}

如果未设置此标头,则删除请求将无法在节点上运行。 您也可以向所需的 url 发出 post 请求,如果没有,则提供删除功能。但设置标题工作正常。

【讨论】:

  • 我的代码上有这个:app.use(function(req, res, next) { res.header('Access-Control-Allow-Origin', "*"); res.header ('Access-Control-Allow-Methods','GET,PUT,POST,DELETE'); res.header('Access-Control-Allow-Headers', 'Content-Type'); next(); }) 但是还是不行
  • 是 req.body 日志记录
  • 什么?没看懂,抱歉
  • 您有一个 console.log,req.body 也在您的终端中登录
  • 哦,是的...没有记录
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-18
  • 2022-12-12
  • 2021-12-04
  • 2020-08-14
  • 1970-01-01
相关资源
最近更新 更多