首页 > 解决方案 > 即使在服务器代码中添加标头后,跨域请求也被阻止

问题描述

我在 Express/Node 中有一个简单的 API,还有一个用于发布博客的简单 Angular 应用程序。唯一的问题是当我/contribute使用 POST 方法到达路线时。我在 chrome 和 firefox 上都遇到了这个错误:

error: error { target: XMLHttpRequest, isTrusted: true, lengthComputable: false, ... } ​ headers: Object { normalizedNames: Map(0), lazyUpdate: null, headers: Map(0) } ​ message: “本地主机的 Http 失败响应:3000/api/contribute: 0 Unknown Error" ​ name: "HttpErrorResponse" ok: false ​ status: 0 ​ statusText: "Unknown Error" ​ url: "localhost:3000/api/contribute" ​ : {…} ​​ 构造函数:类 HttpErrorResponse { 构造函数(init) }​​:{…} ​​​构造函数:类 HttpResponseBase { 构造函数(init,defaultStatus,defaultStatusText)}​​​:{…</p>

这是我的服务器端代码。

api.js

...
router.post('/contribute', (req, res) => {
    console.log('Pushing new article');
    let userPost = req.body;
    let post = new Post(userPost);
    post.save((error, registeredPost) => {
        if (error) {
            console.log(error);
        } else {
            res.status(200).send(registeredPost);
        }
    })
})
...
module.exports = router;

服务器.js

const express = require('express');
const bodyParser = require('body-parser');

const app = express();

const api = require('./routes/api');
const cors = require('cors');

app.use(bodyParser.json());

// app.use(cors({ origin: 'http://localhost:4200' })); <--- TRIED THIS ALSO

app.use(function (req, res, next) {

    // Website you wish to allow to connect
    res.setHeader('Access-Control-Allow-Origin', 'http://localhost:4200');

    // Request methods you wish to allow
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

    // Request headers you wish to allow
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

    // Set to true if you need the website to include cookies in the requests sent
    // to the API (e.g. in case you use sessions)
    res.setHeader('Access-Control-Allow-Credentials', true);

    // Pass to next layer of middleware
    next();
});

app.use('/api', api);
app.get('/', function(req, res) {
    res.send('Server is up and running!');
})

app.listen(3000, function() {
    console.log('Server listening port:3000');
});

是的,服务器已启动并正在运行。

这是角度代码。 auth.service.ts

private _contributeUrl = "https://localhost:3000/api/contribute";
...
pushNewPost(newPost) {
  console.log("here is the new post", newPost); // GETTING CORRECT OUTPUT
  return this._http.post<any>(this._contributeUrl, newPost);
}

贡献.component.ts

this._auth.pushNewPost(this.makeNewPost)
.subscribe (
  res => {
    (<HTMLInputElement>document.getElementById("inputTitle")).value="";
    this.editorForm.reset();
    this.addSingle();
  },
  err => console.log(err)
);

现在有趣的部分是,当我使用 Postman 向这条路线发出发布请求时,相同的代码可以完美运行,没有任何错误。

请纠正我的错误。添加后:

  pushNewPost(newPost) {
    console.log("here is the new post", newPost);
    let headers = new HttpHeaders({
      'Content-Type': 'application/json',
     });
     let options = { headers: headers };
    return this._http.post<any>(this._contributeUrl, newPost);
  }

我得到这个:

在此处输入图像描述

标签: node.jsangularexpress

解决方案


好像您没有从角度发送标题。进行以下更改:

pushNewPost(newPost) {
  // adding the headers
  const headers = new HttpHeaders({
   'Content-Type': 'application/json',
  });
  const options = { headers: headers };

  return this._http.post<any>(this._contributeUrl, newPost, options);
}

推荐阅读