简体   繁体   English

Angular 5节点js表示POST JSON Obj。 到Amazon Aws [外部API](以前称为CORS问题)

[英]Angular 5 node js express POST JSON Obj. to Amazon Aws [External API] (formerly CORS issue)

SOLVED, see my answer below 解决了,请看下面我的回答

My server runs on localhost:3000 我的服务器在localhost:3000上运行

I develop on localhost:4200 我在localhost:4200上开发

I am creating something and trying to post it on an Amazon API 我正在创建某些东西并将其发布到Amazon API上

Angular side code: 角边码:

sendSomething(something) {
    const body = JSON.stringify(something);
    // const headers = new Headers({'Content-Type': 'application/json'});
    const headers = new Headers({'Access-Control-Allow-Origin': '*'});
    return this.http.post('http://Amazon-API:port/send', body, {headers: headers})
      .map((response: Response) => response.json())
      .catch((error: Response) => {
        this.error.handleError(error.json());
        return Observable.throw(error.json());
      });
}

Server side: 服务器端:

//////////////app.js//////////////

app.use(cors());

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", '*'); //<-- you can change this with a specific url like http://localhost:4200
  // res.header("Access-Control-Allow-Credentials", true);
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
  res.header("Access-Control-Allow-Headers", 'Origin,X-Requested-With,Content-Type,Accept,content-type,application/json');
  next();
});


app.use('http://Amazon-API:port', engineRoutes);




//////////////routes/engine.js//////////////

router.post('/send', engine_controller.send_something);



//////////////controllers/engine.controller.js//////////////

exports.send_something = function (req, res, next) {
  const somethingID = req.body.something;
  Something.findById(somethingID, function(err, something) {
    if (err) {
      res.status(404).json({
        title: 'Something not found',
        error: {message: 'Something went wrong'}
      });
    }
    console.log(something);
    if (something) {
      res.status(200).json({
        message: 'Something successfully sent',
        something: something
      });
    }
  })
};

I have tried posting to that API with cors, without cors and with the res.headers appended, and every other variation I could think of 我尝试过使用cors,不带cors和附加res.header以及其他所有我想到的变体形式发布到该API

I still get this error which I've seen so common around here, but still, their solutions don't seem to work for me. 我仍然遇到这个错误,在这里我已经见过如此普遍,但是仍然,他们的解决方案似乎对我不起作用。 Still getting this error... 仍然出现此错误...

Failed to load http://Amazon-API:port/send : Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. 无法加载http:// Amazon-API:port / send :对预检请求的响应未通过访问控制检查:所请求的资源上没有'Access-Control-Allow-Origin'标头。 Origin ' http://localhost:4200 ' is therefore not allowed access. 因此,不允许访问源' http:// localhost:4200 '。 The response had HTTP status code 403. 响应的HTTP状态码为403。

That's from NETWORK tab: 这是在“网络”标签中:

Accept:*/*
Accept-Encoding:gzip, deflate
Accept-Language:he-IL,he;q=0.9,en-US;q=0.8,en;q=0.7
Access-Control-Request-Headers:access-control-allow-origin
Access-Control-Request-Method:POST
Connection:keep-alive
Host:Amazon-API:port
Origin:http://localhost:4200

Any kind of help would be so much appreciated 任何帮助将不胜感激

I see you added this code but I can't post comment yet, you may try to add this code before other routes 我看到您添加了此代码,但目前还无法发表评论,您可以尝试在其他路线之前添加此代码

app.use(function (req, res, next) {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, 
Content-Type, Accept');
    res.setHeader('Access-Control-Allow-Methods', 'POST, GET, PATCH, DELETE, 
OPTIONS');
    next();
});

Solved, 解决了,

What I did was routing back to the server on the front: 我所做的是路由回到前端的服务器:

sendSomething(something) {
  const body = JSON.stringify(something);
  const headers = new Headers({'Content-Type': 'application/json'});
  return this.http.post('http://localhost:3000/api/somethings/send-something', body, {headers: headers})
    .map((response: Response) => response.json())
    .catch((error: Response) => {
      this.error.handleError(error.json());
      return Observable.throw(error.json());
    });
}

And then accepting this route as it is on the back: 然后接受背面的此路线:

//////////////app.js//////////////////

app.use('/api/somethings/send-something', engineRoutes);



/////////////routes/engine.js/////////

router.post('/', engine_controller.send_something);

And most importantly, in the controller itself I used the newly downloaded request lib to send my json data to my external API: 最重要的是,在控制器本身中,我使用了新下载的请求库将json数据发送到我的外部API:

////////////controlllers/engine.controller.js////////////

const request = require('request');

exports.send_something = function (req, res, next) {
  const SomethingID = req.body.something;
  Something.findById(SomethingID, function(err, something) {
    if (err) {
      res.status(404).json({
        title: 'Something not found',
        error: {message: 'Something went wrong'}
      });
    }
    request({
      url: app.get('amazon-API:port/method'),
      method: "POST",
      json: something
    }, function (error, response, body) {
      // console.log(error) <--- returns null or error
      // console.log(response.statusCode <--- returns 200 / 403 / w.e
      // console.log(body) <--- returns response pure html
      res.status(200).json({
        message: 'Something successfully sent',
        response: body,
        status: response.statusCode
      });
    });
  })
};

Now as a response I'm getting what the server which I posted to sends me back, which is exactly what I need. 现在,作为响应,我得到了发布给我的服务器,这正是我所需要的。

Ultimately I figured my way thanks to many other questions posted here 最终,我归因于这里发布的许多其他问题

So thank you SOF once again! 再次感谢SOF!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM