繁体   English   中英

被 CORS 政策阻止 请求的资源上不存在“Access-Control-Allow-Origin”header

[英]Blocked by CORS policy No 'Access-Control-Allow-Origin' header is present on the requested resource

我目前正在做一个项目,将 mysql 的“帖子”发布到网站上,然后它们也可以从网站更新到 Mysql。我的插入 function 工作正常,因为我可以像什么都没有一样添加帖子。 每当我尝试删除帖子时,它都会给我一个很长的 CORS 策略错误。 我已经在整个 inte.net 上寻找答案,但还没有找到解决方案。 我已经尝试在 chrome 中安装 CORS 扩展,并将 header 更改为 no cors。我是正在使用的 API 的所有者。

索引.js

const baseUrl = "**redacted for security**"
//const baseUrl = "https://localhost:5001/api/post"
//update
function getPost(){
    //const allPostsApi = "https://localhost:5001/api/post";
    const allPostsApi = baseUrl;

    fetch(allPostsApi).then(function(response){
        console.log(response);
        return response.json();
    }).then(function(json){
        let html = "<ul>";
        json.forEach((post)=>{
            html += "<li>" + post.text + " Posted by Big Al! </li>";
        })
        html += "</ul>";
        document.getElementById("Post").innerHTML = html;
    }).catch(function(error){
        console.log(error);
    });
}

function handleOnSubmit(){
    console.log("We made it");
    var postText = document.getElementById("text").value;
    //const placeHolder = document.getElementById("Nothing").value;
    //const addPostsApi = "https://localhost:5001/api/post";
    console.log(postText);
    const addPostsApi = baseUrl;
    var text ={ 
        Text: postText
    }

    PlacePost(text);
}

function handleOnEnter(){
    console.log("We made it");
    var postId = document.getElementById("id").value;
    //const placeHolder = document.getElementById("Nothing").value;
    //const addPostsApi = "https://localhost:5001/api/post";
    console.log(postId);
    const addPostsApi = baseUrl;
    var id ={ 
        Text: postId
    }

    RemovePost(postId);
}

function PlacePost(text){
    const PlacePostUrl = baseUrl;
    fetch(PlacePostUrl, {
        method: "POST",
        headers: {
            "Accept": 'application/json',
            "Content-Type": 'application/json'
        },
        body: JSON.stringify(text)
    }).then(response=>{
        getPost();
    })
}

function RemovePost(id){
    const RemovePostUrl = baseUrl;

    fetch(RemovePostUrl, {
        mode: 'cors',
        method: "PUT",
        headers: {
            "Accept":'application/json',
            "Content-Type": 'application/json; charset=UTF-8' 
        },
        body: JSON.stringify(id)
    }).then(response=>{
        getPost();
    })
}

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
    <link href="resources/index.css" rel="stylesheet">
    <title>Document</title>
</head>
<body onload = "getPost()">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
    <script type = "text/javascript" src = "scripts/index.js"></script>
    <div id="Post">

    </div>
    <div class = "row">
        <form id = "addPost" onsumbit ="return false;" method = "post">
            <label for="title">Enter Post</label>
            <input type ="text" name = "text" id ="text">
            <input type ="button" value = "Submit" onclick="handleOnSubmit()">
        </form>
        <form id = "RemovePost" onsubmit ="return false;" method = "put">
            <label for ="title">Enter Post Number you wish to delete</label>
            <input type ="text" name = "text" id ="id">
            <input type ="button" value = "Submit" onclick="handleOnEnter()">
        </form>

    </div>
</body>
</html>

我只是对它在 PlacePost 上的表现感到非常困惑,但在 RemovePost 过程中遇到了问题。 任何和所有的帮助表示赞赏。

删除mode: 'cors'从您的 RemovePostUrl 提取中提取mode: 'cors'

如果您的 js 与您的 API 在同一域上运行,则可以将其设置为same-origin

https://developer.mozilla.org/en-US/docs/Web/API/Request/mode

您 100% 不需要浏览器扩展。

您是否收到任何可以在后端跟踪的错误? 我曾在 Web 应用程序中遇到过 cors 错误,但真正发生的是后端无法处理请求并发送回不正确的响应,并且没有/错误的 http 代码。

如果您尝试使用邮递员删除会发生什么?

使用'npm i cors'

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

app.use(
      cors({
          origin: "*"
      }
));

cors 不关心同源之间的请求。 如果您想允许来自同一来源的请求,那么您可以将来源值设置为您要请求的 URL。 例如origin: 'http://127.0.0.1:8000'如果你只想允许所有 URL 访问你的网站,你可以在 header 中使用origin: '*' ,这将允许来自任何 URL 的跨源请求

希望这可以帮助:)

暂无
暂无

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

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