English 中文(简体)
How to host Express express.static(__dirname) instead of index.html on Azure Static Web Apps?
原标题:

I have been trying to host a basic Chat app on Azure using Express. The server.js file uses the Express middleware of express.static(__dirname) to function properly.

When I test locally on port 3000 I am able to access and update the database.

I tried to replace the "localhost:3000/messages" with my hosted url "example.com/messages" in the html file. Was this correct or should I leave it as localhost? I don t think changing it was correct.

On Azure, I am able to build/run node and host my index.html page as a static web app. But how do I tell Azure to host the server.js file? Since I need to use the express.static() make everything function properly...

Index.html file:

<!DOCTYPE html>
<html lang="en-us">
    
<script type =  application/javascript >

    var socket = io()

    const messageDiv = document.getElementById( messages )

    const settings = {
        url:  example.com/messages 
    }

    async function clearMessages(func) {
        while (messageDiv.firstChild) {
            messageDiv.firstChild.remove()
        }
        await func
    }


    $(() => {
        $( #send ).click(() => {
            sendMessage({
                name: $( #name ).val(),
                message:$( #message ).val()
            })
        })
        getMessages()
    })

    $(() => {
        $( #send2 ).click(() => {
        clearMessages(getMessageOfUser())
        })
    })

    $(() => {
        $( #send3 ).click(() => {
        clearMessages(getAllMessages())
        })
    })
    console.log(messageDiv.firstChild)

    function addMessages(message){
        $( #messages ).append(
            `<h4> ${message.name} </h4>
            <p> ${message.message} </p>`
        )
        console.log( hello )
    }

    function getMessages(){
        $.get(settings, (data) => {
        data.forEach(addMessages);
        })
    }

    function getMessageOfUser(){
        $.get( example.com/messages  + $( #name ).val(), (data) => {
        data.forEach(addMessages);
        })
    }

    function getAllMessages(){
        $.get( example.com/messages/ , (data) => {
        data.forEach(addMessages);
        })
    }
//http://localhost:3000 ?? 



    function sendMessage(message) { 
        $.post(settings, message)
        console.log( cool )
    }

    socket.on( message , addMessages)   

</script>
</body>
</html>

Server.js file:

var express = require( express );
var bodyParser = require( body-parser )
var app = express();
var http = require( http ).Server(app);
var io = require( socket.io )(http);
var mongoose = require( mongoose );

app.use(express.static(__dirname));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}))


var Message = mongoose.model( Message ,{
  name : String,
  message : String
})

var dbUrl =  example.com/mydatabase 

app.get( /messages , async (req, res) => {
    await Message.find({})
    .then((log) => (res.send(log)))
    .catch((err) => {
        console.log(err)
    })
})


app.get( /messages/:user , async (req, res) => {
  var user = req.params.user
  await Message.find({name: user})
  .then((foundUser) => {res.send(foundUser)})
  .catch((err) => console.log(err))
})


app.post( /messages , async (req, res) => {
  try{
    var message = new Message(req.body);

    var savedMessage = await message.save()
      console.log( saved );

    var censored = await Message.findOne({message: badword });
      if(censored)
        await Message.remove({_id: censored.id})
      else
        io.emit( message , req.body);
      res.sendStatus(200);
  }
  catch (error){
    res.sendStatus(500);
    return console.log( error ,error);
  }
  finally{
    console.log( Message Posted )
  }

})



io.on( connection , () =>{
  console.log( a user is connected )
})

mongoose.connect(dbUrl) 


var server = http.listen(3000, () => {
  console.log( server is running on port , server.address().port);
});

azure-static-web-apps.yaml file:

name: Azure Static Web Apps CI/CD

pr:
  branches:
    include:
      - main
trigger:
  branches:
    include:
      - main

jobs:
- job: build_and_deploy_job
  displayName: Build and Deploy Job
  condition: or(eq(variables[ Build.Reason ],  Manual ),or(eq(variables[ Build.Reason ],  PullRequest ),eq(variables[ Build.Reason ],  IndividualCI )))
  pool:
    vmImage: ubuntu-latest
  variables:
  - group: Azure-Static-Web-Apps-agreeable-stone-0e4ff3810-variable-group
  steps:
  - checkout: self
    submodules: true
  - task: AzureStaticWebApp@0
    inputs:
      azure_static_web_apps_api_token: $(AZURE_STATIC_WEB_APPS_API_TOKEN_AGREEABLE_STONE_0E4FF3810)
###### Repository/Build Configurations - These values can be configured to match your app requirements. ######
# For more information regarding Static Web App workflow configurations, please visit: https://aka.ms/swaworkflowconfig
      app_location: "/" # App source code path
      api_location: "" # Api source code path - optional
      output_location: "/" # Built app content directory - optional
###### End of Repository/Build Configurations ######

I was hoping to have my application deploy properly on Azure to have all the functionality of server.js using express.static(__dir) and allow the user to query and add to my database on mongoose atlas.

Is express.static() a bad replacement for actual routing? Am I missing something? I am still new to node, express and azure. Thanks

问题回答

暂无回答




相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.

热门标签