简体   繁体   English

PUG NodeJS Express 前端/后端无连接

[英]PUG NodeJS Express Front End / Backend no connection

Hello i have two NodeJS running on my sever你好,我的服务器上运行着两个 NodeJS

please this is only a dev machine not production so i know parsing the form data etc etc请这只是一个开发机器而不是生产所以我知道解析表单数据等

App.js - Backend Express Sever running on port 4000 App.js - 在端口 4000 上运行的后端 Express Sever

index.js - Front End PUG/Express running on port 8000 index.js - 在端口 8000 上运行的前端 PUG/Express

i can access the frontend on something.mydomain.com我可以在 something.mydomain.com 上访问前端

but when i try to ajax the backend with 'POST' to localhost:4000/Whatever/Whatever但是当我尝试使用 'POST' 将后端 ajax 发送到 localhost:4000/Whatever/Whatever

it doesnt allow me to.它不允许我这样做。

as in it tries to load locahost from the WWW external not internal login.js因为它试图从 WWW 外部而不是内部 login.js 加载 locahost

 const serverurl = "http://localhost:4000"; $(document).ready(function () { $('#login').click(function () { var data = {}; data.username = $('#inputusername').val(); data.password = $('#inputpassword').val(); $.ajax({ url: serverurl+'/user/login' , type: 'POST' , data: JSON.stringify(data) , contentType: 'application/json' }) .done(function (data) { if (data[0].response == '1') { alert("Logged In"); Cookies.set('user', data[0].name); Cookies.set('location', data[0].location); Cookies.set('role', data[0].role); $(location).attr('href', '/home'); } else if(data[0].response == '0') alert("Username or Password Incorrect") }); });

frontend request image前端请求图片

Any help will be appreciated任何帮助将不胜感激

You got CORS error.你有 CORS 错误。 You can reach more info about it .您可以访问有关它的更多信息 My solution is using for Express.js CORS package我的解决方案用于 Express.js CORS 包

Your main js file should be like:你的主要 js 文件应该是这样的:

// app.js
const express = require('express')
const cors = require('cors')
const app = express()

app.use(cors())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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