当我试图在另一台电脑上 运行 时,Cors 请求没有成功

Cors request did not succeed when im trying to run it on another pc

所以我使用 nodejs 开发网站,然后将其部署到 Microsoft azure,准确地说,使用 Azure 数据库作为 mysql 服务器,并使用 mysql workbench 导入我的数据库,现在问题出在 CORS 上,一切顺利,我 运行 它在 chrome 上,同一台电脑上的 firefox 工作正常,但是当我尝试使用另一台电脑访问该网站时,我收到错误说“跨源请求被阻止:同源策略不允许读取位于 http://localhost:3000/data/price%20asc 的远程资源。(原因:CORS 请求未成功)”。

这是我的 nodejs 代码:

//use path module
const path = require("path");
//use express module
const express = require("express");
//use hbs view engine
// const hbs = require('hbs');
//use bodyParser middleware
const bodyParser = require("body-parser");
//use mysql database
const mysql = require("mysql");
const app = express();
const db = require("./database");

//cors
const cors = require("cors");

// app.use(cors());

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

app.use(function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept"
  );
  next();
});

//konfigurasi koneksi
const conn = mysql.createConnection({
  // host: 'localhost',
  // user: 'root',
  // password: '',
  // database: 'domdom'

  host: "domdom.mysql.database.azure.com",
  user: "domdom@domdom",
  password: "Banana123",
  database: "schema1",
  port: 3306,
  ssl: true,
});

//connect ke database
conn.connect((err) => {
  if (err) throw err;
  console.log("Mysql Connected...");
});

//set views file
app.set("views", path.join(__dirname, "/"));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.json());
app.use(express.static(__dirname));

app.param("productname", function (request, response, next, product) {
  // ... Perform database query and
  // ... Store the user object from the database in the req object
  request.product = product;
  return next();
});

app.param("sort", function (request, response, next, price) {
  // ... Perform database query and
  // ... Store the user object from the database in the req object
  request.price = price;
  return next();
});

app.param("id", function (request, response, next, id) {
  // ... Perform database query and
  // ... Store the user object from the database in the req object
  request.id = id;
  ß;
  return next();
});

//get all data
app.get("/data/:sort", (req, res) => {
  let sql = "SELECT * FROM products Order By " + req.price;
  let query = conn.query(sql, (err, results) => {
    res.json(results);
  });
});

//untuk search and sort
app.get("/data/:productname/:sort", function (req, res) {
  let sql =
    "SELECT * FROM products WHERE name like '%" +
    req.product +
    "%' Order By " +
    req.price;
  let query = conn.query(sql, (err, results) => {
    res.json(results);
  });
});

//untuk save data
app.post("/save/:id", (req, res) => {
  let sql =
    "INSERT INTO cart SELECT * from products WHERE id = '" + req.id + "'";
  let query = conn.query(sql, (err, results) => {
    if (err) throw err;
    res.redirect("/");
  });
});

//render interface
app.get("/", (req, res) => {
  res.render("index");
});

//server listening
app.listen(3000, () => {
  console.log("Server is running at port 3000");
});

正如您在代码中看到的那样,我已经尝试了 3 种方法来解决这个问题,但都没有用,请帮忙。

如果您使用 Azure 应用服务来托管您的 nodejs 应用,在 Azure 门户上配置 CORS 的最快方法 => 应用服务 => CORS :

我自己做了一些测试,这是我的 nodejs 服务器代码(如您所见,没有 CORS 配置):

const express = require('express')
const app = express()
const port = process.env.PORT || 8080

app.use(express.json())

app.get('/', (req, res) => {
  res.send('Hello World!')
})

app.post('/', (req, res) => {
  var body = req.body;

  res.send(`Hello ${body.name}!`)
})

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})

测试来自本地静态网页的 HTTP 请求:

<!DOCTYPE html>
<html>
<body>

<h1>The XMLHttpRequest Object</h1>

<button type="button" onclick="loadDoc()">Request data</button>

<p id="demo"></p>


<script>
function loadDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("demo").innerHTML = this.responseText;
    }
  };
  xhttp.open("POST", "https://nodeweb05.azurewebsites.net/", true);
  xhttp.setRequestHeader("Content-type", "application/json");
  var body = {"name":"testuser"};
  xhttp.send(JSON.stringify(body));
}
</script>

</body>
</html>
你可以自己试试。

如果您想在代码级别配置 CORS,只需尝试以下配置:

const express = require('express')
const app = express()
var cors = require('cors')
app.use(cors())