简体   繁体   中英

Express-API POST works in Postman but not with AJAX

I want to make an AJAX call in Javascript to my ExpressJS Rest API.

However with Javascript the POST-call does not work.

In Postman the same JSON-data with the same Headers works.

This is the error in js (ajax):

cross-origion Request Blocked: The Same Origin Policy disallows reading the remote resource at http://192.168.10.106:8080/api/cart/. (Reason: CORS header 'Access-Control-Allow.Origin' missing)

This is the error in node.js:

SyntaxError: Unexpected token c in JSON at position 0
    at JSON.parse (<anonymous>)

Cors are enabled. Headers are set in the AJAX (Content-Type, ...)

API-Code:

const express = require('express');
const app = express();
var cors = require('cors');

app.use(express.json());
app.use(cors());
app.options('*', cors());
app.all('/*', function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.setHeader("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
  res.setHeader("Access-Control-Allow-Headers", "Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

app.post('/api/cart', async (req, res) => {
    res.send(true);
});

app.listen(8080, () => {
  console.log('Example app listening on port 8080!');
});

AJAX-Code:

$.ajax({
                  url:"http://192.168.10.106:8080/api/cart/",
                  type:"POST", //First change type to method here
                  headers: {
                    'X-Requested-With':  'XMLHttpRequest',
                    'Accept': '*/*',
                    'Cache-Control':'no-cache',
                  },
                  contentType: "application/json; charset=utf-8",
                  data:{
                    JSON.stringify(cart)
                  },
                  success:function(response) {
                  },
                  error:function(data, data1, data2){
                    console.log(data1);
                    alert("An Error occurred. Try again later");
                  }
              });

I expect the post-api be executed with this ajax code.

However this is not the case. Any ideas?

I think you need to change you ajax to this:

$.ajax({
                  url:"http://192.168.10.106:8080/api/cart/",
                  type:"POST", //First change type to method here
                  headers: {
                    'X-Requested-With':  'XMLHttpRequest',
                    'Accept': '*/*',
                    'Cache-Control':'no-cache',
                  },
                  contentType: "application/json; charset=utf-8",
                  data: JSON.stringify(cart),
                  success:function(response) {
                  },
                  error:function(data, data1, data2){
                    console.log(data1);
                    alert("An Error occurred. Try again later");
                  }
              });
  $.ajax({
    url:"http://192.168.10.106:8080/api/cart/",
    type:"POST", //First change type to method here
    headers: {
      'X-Requested-With':  'XMLHttpRequest',
      'Accept': '*/*',
      'Cache-Control':'no-cache',
      "contentType": "application/json; charset=utf-8"
    },

    data:{
      "itemId": 1234
    },
    success:function(response) {
        console.log(response);
    },
    error:function(data, data1, data2){
      console.log(data1);
      alert("An Error occurred. Try again later");
    }
});

Replace your ajax code with above code

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