【问题标题】:Access-Control-Allow-Origin header is present, but I'm still gettings CORS errors [duplicate]Access-Control-Allow-Origin 标头存在,但我仍然收到 CORS 错误 [重复]
【发布时间】:2020-07-11 23:43:34
【问题描述】:

我正在尝试向快速服务器发出 GET 请求,但出现错误:“跨源请求被阻止:同源策略不允许读取 http://localhost:3002/ 上的远程资源嘿。(原因:CORS 标头 'Access-Control-Allow-Origin' 缺失)"

在前端

fetch('http://localhost:3002/hey', {
        method: "GET", 
        headers: {
            'Access-Control-Allow-Origin': 'http://localhost:3000'
        }
    })
    .then(response => response.text())
    .then(data => {
        console.log(data);
        this.setState({ apiResponse: data })
    });

在后端

const express = require('express');
const cors = require('cors');
const app = express();

app.use(cors());

app.listen(3002, () => {
    console.log('server is running on port 3002');
})

app.get('/hey', (req, res, next) => {
    res.send('ho');
})

【问题讨论】:

标签: javascript rest express


【解决方案1】:

HTTP 有请求和响应。

请求处于高级别:

  1. URI
  2. 方法
  3. 标题
  4. 身体

回复通常是:

  1. 状态
  2. 标题
  3. 身体

您在请求中在客户端上发送 Access-Control-Allow-Origin 标头。此标头需要由服务器在响应中发送。

【讨论】:

    猜你喜欢
    • 2016-11-06
    • 2014-08-20
    • 2021-05-23
    • 1970-01-01
    • 2016-10-30
    • 1970-01-01
    • 2021-12-02
    • 2018-09-19
    • 2016-05-07
    相关资源
    最近更新 更多