【问题标题】:MERN simple app CORS error issue - POST requestMERN 简单应用 CORS 错误问题 - POST 请求
【发布时间】:2022-02-17 20:22:49
【问题描述】:

我明白了,

Access to fetch at 'http://localhost:9000/api/v1/content' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

对于我的 FE(反应) 并获取 BE(node) 的语法错误,

SyntaxError: Unexpected token " in JSON at position 0

我对 GET 请求没有任何问题,但我不能 POST。 这是我的FE

  addContent = async (e) => {
    e.preventDefault();

    try {
      const response = await fetch('http://localhost:9000/api/v1/content', {
        method: 'POST',
        body: JSON.stringify(this.state.title),
        // mode:'cors', --> tried after researching but it didn't solve my issue
        headers: {
          'Content-Type': 'application/json'
        }
      });

      if(!response.ok) {
        throw Error(response.statusText)
      }

    } catch (err) {
      console.log('addContent failed -', err)
    }
  }

这是我的BE

  origin: ['http://localhost:3000', 'https://localhost:3000'],
  credentials: true,
  optionsSuccessStatus:200
}

app.use(cors(corsOptions));

另外,当我使用邮递员 POST 时,我能够 POST(得到 200)但是,它只返回 _id。没有正文(我要发布的内容标题)

我阅读了许多解释 cors 问题的文章,但我找不到解决问题的正确答案。请假设我是编程的初学者。谢谢你!!

【问题讨论】:

    标签: node.js reactjs


    【解决方案1】:

    试试这个

    addContent = async (e) => {
        e.preventDefault();
    
        try {
          const response = await fetch('http://localhost:9000/api/v1/content', {
            method: 'POST',
            body: JSON.stringify(this.state.title),
            // mode:'cors', --> tried after researching but it didn't solve my issue
            headers: {
              'Access-Control-Allow-Origin': '*',
              'Content-Type': 'application/json'
    
            }
          });
    
          if(!response.ok) {
            throw Error(response.statusText)
          }
    
        } catch (err) {
          console.log('addContent failed -', err)
        }
      }
    
    

    你也可以参考https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

    我建议在 express 不使用 cors 的情况下尝试一次。

      origin: ['http://localhost:3000', 'https://localhost:3000'],
      credentials: true,
      optionsSuccessStatus:200
    }
    
    //app.use(cors(corsOptions));
    

    【讨论】:

    • 感谢您的帮助@Shivprasad。我都试过了,他们都给我返回了这些错误。 localhost/:1 Access to fetch at 'http://localhost:9000/api/v1/content' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
    • 我想知道为什么我在BE得到SyntaxError: Unexpected token " in JSON at position 0
    • 你从服务器返回的数据格式是什么?
    • 感谢您再次回复我。我只是想通了。问题是 this.state.content.title 不仅仅是标题 - 因为这是我在服务器端设计代码的方式。再次感谢您!
    【解决方案2】:

    这里的错误意味着您不允许从任何其他 URL 访问 localhost:9000。 我建议你看看这个 (https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS)

    如果您希望任何人都可以访问您的 API,您可以将“Access-Control-Allow-Origin”标头设置为“*”。 这是此标头用途的完整说明 (https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin)。

    希望对你有用。

    【讨论】:

    • 那么我应该在我的代码中的哪个位置添加它?对不起,我是编程的初学者。我阅读了您所有的参考链接,但没有找到解决方案。你能告诉我我应该添加哪一行代码吗?
    猜你喜欢
    • 1970-01-01
    • 2020-06-07
    • 2020-12-20
    • 1970-01-01
    • 2020-10-04
    • 2021-11-02
    • 2017-06-08
    • 2020-12-13
    • 2021-08-22
    相关资源
    最近更新 更多