简体   繁体   中英

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

so im developing website using nodejs, and then deploying it to microsoft azure, and using Azure Database for mysql server to be exact, and importing my databse using mysql workbench, now the problem is in the CORS, everyhting going well i run it on chrome and firefox in the same pc works fine, but when i try to acces the website using another pc, i get the error says "Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:3000/data/price%20asc. (Reason: CORS request did not succeed)".

heres my nodejs code:

//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");
});

as you can see in the code i have tried 3 ways trying to solve this problem, but nothing works, please help.

If you are using Azure app service to host your nodejs app,the most fastest way to config CORS on Azure Portal => app service => CORS:

在此处输入图像描述

I did some test on my side and this is my nodejs server code(as you can see, no config for 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}`)
})

Test HTTP request from an local static web page:

 <;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>
You can try it yourself.

If you want to config CORS on code level, just try the config below:

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

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.

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