简体   繁体   中英

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

I'm currently making a project to put up "Post" from mysql onto a website and then they can also be updated from the website into Mysql. My insert function works fine because I can add post like nothing. Whenever I try and delete a post it gives me a long CORS policy error. I've looked all over the inte.net for an answer, but haven't found a solution. I've tried installing the CORS extensions in chrome and to also change the header into no cors. I'm the owner of the API being used.

index.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>

I'm just very confused on how it does through on the PlacePost, but gets caught up during RemovePost. Any and all help is appreciated.

Remove mode: 'cors' from your RemovePostUrl fetch.

You could set it to same-origin if your js is running on the same domain as your API.

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

You 100% do not need a browser extension.

Are you getting any errors that you can trace in your backend? I have experienced getting cors errors in web apps but what really happened was that the backend failed to process the request and sent back incorrect responses with no/faulty http codes.

What happens if you attempt to delete using postman?

install 'cors' by using 'npm i cors'

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

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

cors does not care about requests between the same origin. If you want to allow request from an within the same origin then you can set the origin value to the URL you want to request. eg origin: 'http://127.0.0.1:8000' And if you want to just allow all URLs to access your site you can instead use origin: '*' in the header and that will allow cross origin requests from any URL

Hope this helps:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

Related Question Access to fetch has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource localhost:4200 has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource fetch has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource Javascript XMLHttpRequest - has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource in Javascript React component has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource Access to fetch `url` been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. ReactJS Blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource Error In Socket.io Error How to Resolve? One function of my webpage has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource How to fix ''http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM