POST JSON with iron-ajax to SQL Server with Node

POST JSON with iron-ajax to SQL Server with Node

我正在尝试 return 来自 Polymer 登录的用户数据。我在 Postman 中使用它,但在将它转换为 Polymer 时遇到了问题。

在 Postman 中,此 return 是一个 JSON 对象,但在 Polymer 中,它是 returning undefined

Polymer 客户端代码[连接到 node.js 服务器]

<iron-ajax id="ajaxUser"
  url="http://localhost:8080/login"
  method="post"
  handle-as="json"
  content-type="application/json"
  headers='{"Access-Control-Allow-Origin": "*"}'
  params="[[params]]"
  on-response="saveUserCredentials"
  last-response="{{user}}"></iron-ajax>

...

<paper-input id="username"></paper-input>
<paper-input id="password"></paper-input>
<paper-button on-tap="loginUser"></paper-button>

...

loginUser() {
  this.params = {"username": this.$.username.value, "password": this.$.password.value};
  console.log(this.params); // logs this.params as populated JSON 
  let request = this.$.ajaxUser.generateRequest();
  request.completes.then(req => {
    console.log(req);       // logs <iron-request></iron-request>
    console.log(this.user); // logs []
  })
  .catch(rejected => {
    console.log(rejected.request); // not returned
    console.log(rejected.error);   // not returned
  })
}

saveUserCredentials() {
  console.log(this.user);
}

Node、Express、mssql 服务器代码[连接到 SQL 服务器数据库]

app.post("/login", (req, res) => {
  session.login(req, res)
})

...

exports.login = (req, res) => {
  sql.connect(config.properties)
    .then(pool => {
      pool.request()
        .input('user', sql.VarChar(50), req.body.username)
        .input('password', sql.VarChar(50), req.body.password)
        .query("SELECT role FROM Login WHERE username = @user AND password = @password")
        .then(response => res.send(response))
        .catch(err => res.send(err))
    })
}

错误

SyntaxError: Unexpected token # in JSON at position 0 . at JSON.parse ()
at createStrictSyntaxError (C:\node_modules\body-parser\lib\types\json.js:157:10) at parse (C:\node_modules\body-parser\lib\types\json.js:83:15)
at C:\node_modules\body-parser\lib\read.js:121:18 . at invokeCallback (C:\node_modules\raw-body\index.js:224:16)
at done (C:\node_modules\raw-body\index.js:213:7)
at IncomingMessage.onEnd (C:\node_modules\raw-body\index.js:273:7)
at IncomingMessage.emit (events.js:159:13)
at endReadableNT (_stream_readable.js:1062:12)
at process._tickCallback (internal/process/next_tick.js:152:19)

第一个问题似乎是您的服务器期望请求中包含 JSON object,但由于缺少 Content-Type [,服务器将请求视为字符串=36=] 根据您的要求。要为 JSON 请求设置 Content-Type,请将 <iron-ajax>.contentType 设置为 application/json:

<iron-ajax content-type="application/json" ...>

OK, I was able to get a server response by setting content-type=application/json as an iron-ajax property. Am now getting Unexpected token # in JSON at position 0 as a server side error...

听起来请求实际上无效 JSON(因为它包含 # 作为第一个字符)。使用 Chrome DevTools 网络面板检查负载的实际内容。我不会仅仅依赖你代码中的 console.log

Also, it is now making two requests when I submit. One with the content-type set, which resolves to 200, and one with that resolves to 400 with parsing error.

第一条消息可能是 preflight request, which is sent (as part of CORS) 到服务器以检查 content-type="application/json" 是否是允许的 header。第二条消息是预期的数据请求,但失败并出现以下错误。

And a client side error of No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4001' is therefore not allowed access. The response had HTTP status code 400.

您的服务器需要启用 CORS 请求。有多种方法可以实现这一点,但最简单的 Node 解决方案可能是使用 cors 包:

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