拒绝连接到“http://localhost:3001/user/signup”,因为它使用 React 和 Node Js 违反了文档的内容安全策略

问题描述 投票:0回答:1

我正在使用 React 创建一个注册页面,对于我的后端,我使用 Node JS。当我尝试调用后端的注册 api 时,出现以下错误 api.js:31 拒绝连接到“http://localhost:3001/user/signup”,因为它违反了文档的内容安全策略。 我使用以下示例函数只是为了首先连接到后端 api,然后我将集成真实的表单数据。

export const postAPIWithoutHeader = async () => {
    console.log("postAPIWithoutHeader")
    console.log(body)
  try {
    var myHeaders = new Headers();
    myHeaders.append("Content-Type", "application/json");

     var raw = JSON.stringify({
    "name": "some",
    "email": "[email protected]",
    "password": "Password234@",
    "role": "1",
    "require_servie": true
    });

    var requestOptions = {
    method: 'POST',
    headers: myHeaders,
    body: raw,
    redirect: 'follow'
    };

    let res = fetch("http://localhost:3001/user/signup", requestOptions)
      .then(response => response.text())
      .then(result => console.log(result))
      .catch(error => console.log('error', error));
    
    // console.log(reqBod)
    console.log("res",res)
    return res.data
  } catch (err) {

    console.log("the error we get is ",err);
    return err
  }
}

在我的节点后端,我允许在后端的 app.js 中使用以下代码

const corsOptions ={
    origin:['http://localhost:3000','http://localhost:3003'], 
    credentials:true,
    methods:"POST, GET, OPTIONS",
    optionSuccessStatus:200
};


app.use(cors(corsOptions))
app.options('*', cors(corsOptions));

我已经使用邮递员测试了该应用程序,它可以使用相同的 URL 正常工作。 任何帮助将非常感激

我期待从后端 api 得到响应。

javascript reactjs node.js next.js frontend
1个回答
0
投票

尝试以下配置将域列入白名单

app.use((req, res, next) => {
  const allowedOrigins = ['http://localhost:3000','http://localhost:3003'];
  const origin = req.headers.origin;
  if (allowedOrigins.includes(origin)) {
       res.setHeader('Access-Control-Allow-Origin', origin);
  }
  res.header('Access-Control-Allow-Methods', 'GET, OPTIONS'); // add all the methods you want to add
  res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
  res.header('Access-Control-Allow-Credentials', true);
  return next();
});
© www.soinside.com 2019 - 2024. All rights reserved.