选项已被CORS阻止

时间:2019-02-18 22:10:57

标签: node.js reactjs http express cors

我正在编写一个应答应用程序,该应用程序应使用aws ec2上托管的API的“ Content-Type”:“ application / json”调用POST端点,我在使用cors时遇到了麻烦。

这是我的api代码的一部分

const express = require("express")
const app = new express
const cors = require("cors")

app.all("*", (req, res, next) => {
  console.log("cheeeck")
  res.header("Access-Control-Allow-Origin", "*")
  res.header("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE, OPTIONS")
  res.header("Access-Control-Allow-Headers", "Content-Type, Authorization, Content-Length, X-Requested-With")
  next()
})

app.options("*", (req, res) => {
  console.log("cheeeque")
  res.sendStatus(200)
})    

我认为足以执行此呼叫:

    fetch(urlLogin, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        user: document.getElementById("username").value,
        password: document.getElementById("password").value
      })
    })
      .then(res => res.json())
      .then(res => {
        if(res.status === 200) {

        } else {
          document.getElementById("errorManager").innerHTML = "Wrong username or password"
        }
      })
      .catch(err => {
        console.log(err)
      })

但是当我调用它时,出现typeError:无法获取

Fetch failed loading: OPTIONS "http://mep.re:8080/login".

我还尝试在服务器端使用cors模块,添加以下行:

app.options("*", cors())
app.use(cors())

但它没有改变

,当我尝试从这样的浏览器拨打电话时:

fetch("http://mep.re:8080/login", {method: "OPTION"}).then(console.log).catch(console.log)

我收到此错误:

Access to fetch at 'http://mep.re:8080/login' from origin 'http://localhost:3000' has been blocked by CORS policy: Method OPTION is not allowed by Access-Control-Allow-Methods in preflight response.

我不明白为什么,因为OPTION应该是一种授权方法吗?

当我尝试执行帖子通话时

fetch("http://mep.re:8080/login", {method: "Post", headers: {"Content-type": "application/json"}}).then(console.log).catch(console.log)

这是错误:

Fetch finished loading: OPTIONS "http://mep.re:8080/login".
POST http://mep.re:8080/login 401 (Unauthorized)
Response {type: "cors", url: "http://mep.re:8080/login", redirected: false, status: 401, ok: false, …}body: (...)bodyUsed: falseheaders: Headers {}ok: falseredirected: falsestatus: 401statusText: "Unauthorized"type: "cors"url: "http://mep.re:8080/login"__proto__: Response
Fetch failed loading: POST "http://mep.re:8080/login".

1 个答案:

答案 0 :(得分:-2)

好吧,这很正常,未授权的401是由api上的错误引起的,但是cors运行良好,谢谢大家,对此深表歉意。